/*
 * ------------------------------------------------------------------------------------------------------------
 *      Instructions for setting the Counter Values
 * ------------------------------------------------------------------------------------------------------------
 *
 * - To update counter value call function updateCounter('YourCounterID',valueINT);
 *    Where YourCounterID is the id of your counter div, and valueINT is the value you want to set on the counter
 *
 * Note that there is also a function: inputValueChanged(value)
 * - This function is called when the input value in the input text-field is changed by the user
 * - Modify the logic in the function inputValueChanged() to match your calculation
 *
 */

function initSubTabs(tabs)
{
    if(tabs.length > 0)
    {
        for(var i = 0; i < tabs.length; i++)
        {
            var $currentTab = $('.SubNav .' + tabs[i]);
            $currentTab.bind('click', {currTab: tabs[i]}, handleSubTabClick);
        }
        $('.SubNav .' + tabs[0]).children().addClass('Active');
    }
}

function handleSubTabClick(e)
{
    var currTab = e.data.currTab;
    $('.SubNav a.Active').removeClass('Active');
    $(this).children().addClass('Active');
    $('.Sub .Main').css('display','none');
    $('.Sub .'+currTab+'Content').css('display','block');
    return false;
}

function initGoogleMap(mapCanvasId, centerPoint, zoomLevel, remainingPoints, useControl)
{
    if(GBrowserIsCompatible())
	{
	    if(document.getElementById(mapCanvasId))
	    {
	    	var map = new GMap2(document.getElementById(mapCanvasId));
    		
		    // The GUnload() function is a utility function designed to prevent memory leaks.
		    $(window).unload( function () { GUnload(); } );
    		
		    var centerMarker = new GMarker(centerPoint);
		    map.addOverlay(centerMarker);
		    if (remainingPoints.length > 0)
		    {		    	
		    	centerMarker.setImage(G_IMAGE_PATH + "/map_selected_marker.png");		    	
		    }
		    
		    map.setCenter(centerPoint, zoomLevel);		    // need to be set both here and below for some reason
    		
		    if (useControl === true)
		    {
		    	map.addControl(new GSmallZoomControl3D());
		    	// add map-types control
		    	map.addMapType(G_NORMAL_MAP);
		    	map.addMapType(G_SATELLITE_MAP);
		    	map.addMapType(G_HYBRID_MAP);
		    	var mapControl = new GMapTypeControl();
                map.addControl(mapControl);
                //map.addControl(new GLargeMapControl());
                // (end) add map-types control
		    }
		    var bounds = new GLatLngBounds();
		    for(var i = 0; i < remainingPoints.length; i++)
		    {
		        var point = new GLatLng(remainingPoints[i][0], remainingPoints[i][1]);
		        bounds.extend(point);
		        map.addOverlay(new GMarker(point));
		    }
		    if (remainingPoints.length > 1)
		    {
		    	zoomLevel = map.getBoundsZoomLevel(bounds);
		    	var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
		    	var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
		    }
		    map.setCenter(centerPoint, zoomLevel);
		}
	}
	else
	{
		//alert('Your browser is not compatible with Google Maps');
	}
}

function initOverlay()
{
	resetOverlayHeight();
	
	$(window).resize(function(){
		resetOverlayHeight();
	});
	
	$('.CustomLiteBox .CloseBtn').click(function(){
		hideCustomLiteBox();
	});
}

function hideCustomLiteBox()
{
	$('#CustomLiteBoxElements').css('display','none');
	$('#CustomLiteBoxElements').children('.ShowError').removeClass('ShowError');
	$('#CustomLiteBoxElements').children('.CustomLiteBoxWrap').removeClass('ShowMap');
	$('#CustomLiteBoxElements').children('.CustomLiteBoxWrap').removeClass('ShowTerms');
}

function showCustomLiteBox()
{
	window.scrollTo(0, 0);
	$('#CustomLiteBoxElements').css('display','block');
}

function showError(msg)
{
    $('#CustomLiteBoxElements').css('display','block');
    $('#CustomLiteBoxElements').children('.CustomLiteBoxWrap').addClass('ShowError');
    $('#CustomLiteBoxElements').find('.ErrorMsg').html(msg);
}

function showBigMap()
{
	$('#CustomLiteBoxElements').children('.CustomLiteBoxWrap').addClass('ShowMap');
    $('#CustomLiteBoxElements').css('display','block');
}

function showTerms()
{
	$('#CustomLiteBoxElements').children('.CustomLiteBoxWrap').addClass('ShowTerms');
	$('#CustomLiteBoxElements').css('display','block');
}

function resetOverlayHeight()
{
	if($.browser.safari)
	{
		$('.Overlay').css('height',$(window).height()); // height of browser viewport
		$('.CustomLiteBoxWrap').css('height',$(window).height()); // height of browser viewport
	}
	else if($.browser.msie)
	{
	/*
	    var $temp = $temp("<div>")
	        .css("position","absolute")
	        .css("left","-10000px")
	        .append($temp("body").html());
	        
	    $("body").append($temp);
	    var h = $temp.height();
	    $temp.remove();
	    $('.Overlay').css('height',h); // height of browser viewport
		$('.CustomLiteBoxWrap').css('height',h); // height of browser viewport
		
		alert(h + "\nfrom jquery_functions.js" );*/
	}
	else
	{
		$('.Overlay').css('height',$(document).height()); // height of HTML document
		$('.CustomLiteBoxWrap').css('height',$(document).height()); // height of HTML document
	}
	//alert($(document).height() + "\nfrom jquery_functions.js" );
}

/* Sets the grade on Page 4, accepts a value between 0 and 5 */
function setGrade(value)
{
	if(value < 0 || value > 5)
	{
		value = 0;
	}	
	value = (value * 20) - 100;
	$('.Reliability .Grade').css('backgroundPosition', value+'px 0');
}

function disableLinkClick($handle)
{
	$handle.click(function(){
		return false;
	});	
}

// --------------------------------------------
//		Slider
// --------------------------------------------

function initSlider(sliderWrapID, sliderID, sliderInputID, minVal, maxVal, step, animate)
{
	$('#'+sliderID).slider({
		animate: animate,
		min: minVal,
		max: maxVal,
		step: step
	});
	
	bindSliderInputKeyUp($('#'+sliderInputID), $('#'+sliderID));
	bindSliderSlide($('#'+sliderID), $('#'+sliderInputID));
	bindSliderChange($('#'+sliderID), $('#'+sliderInputID));
	bindSliderWrapClick($('#'+sliderWrapID), $('#'+sliderID));
	bindSliderBlur($('#'+sliderID), $('#'+sliderInputID));
	var slider = jQuery('#' + sliderID); 
	if (slider.length > 0)
	{
		lockSlider(slider);
	}
}

function getRestrictedSliderValue($slider, value)
{
	var maxVal = $slider.slider('option', 'max');
	var minVal = $slider.slider('option', 'min');
	value = Math.min(maxVal, value);
	value = Math.max(minVal, value);
	return value;
}

function bindSliderBlur($slider, $input)
{
	$input.change(function(event){
		var value = getRestrictedSliderValue($slider, $slider.slider('value'));
		$slider.slider('value', value);
		$input.attr('value', value);
		pageObj.onSliderChange();
	});	
}


function bindSliderInputKeyUp($input, $slider)
{
	$input.keyup(function(event){
		var value = getRestrictedSliderValue($slider, $(this).attr('value'));
		$slider.slider('option', 'value', value);		
		updateSliderCover($slider, value);
		//inputValueChanged($(this).attr('value')); // [MERGED]
	});	
}

function bindSliderSlide($slider,$input)
{
	$slider.bind('slide', function(event, ui){
		$input.attr('value',ui.value);
		updateSliderCover($slider);
	});
}

function bindSliderChange($slider, $input)
{
	$slider.bind('slidechange', function(event, ui){
		ui.value = getRestrictedSliderValue($slider, ui.value);
		$input.attr('value',ui.value);
		pageObj.onSliderChange();
		//inputValueChanged(ui.value);
		updateSliderCover($slider,ui.value);
		
		/*
		// Update slider cover width
		var coverWidth = (ui.value/$slider.slider('option','max'));
		coverWidth *= 310; // 310 is the sliderBG width minus 6 pixels (actual width is 316.. set 310 to work around overflow on the right rim)
		$slider.children('.SliderWrapCover').css('width',coverWidth);
		*/
	});
}

function lockSlider($slider)
{
	$slider.slider('disable');
	$slider.closest('.ModuleSlider').find('input').attr('disabled', 'disabled');
}

function unlockSlider($slider)
{
	$slider.slider('enable');
	$slider.closest('.ModuleSlider').find('input').removeAttr('disabled');
}

function updateSliderCover($slider, value)
{
	var coverWidth;
	
	if(value)
	{
		var delta = value - $slider.slider('option','min');
		var range = $slider.slider('option','max') - $slider.slider('option','min'); 
		coverWidth = (delta/range);
		coverWidth *= 310; // 310 is the sliderBG width minus 6 pixels (actual width is 316.. set 310 to work around overflow on the right rim)
		//$slider.children('.SliderWrapCover').css('width',coverWidth);
	}
	else
	{
		var leftPos = $slider.children('.ui-slider-handle').css('left');
		leftPos = leftPos.replace('%','');
		leftPos /= 100;
		coverWidth = leftPos * 310; // 310 is the sliderBG width minus 6 pixels (actual width is 316.. set 310 to work around overflow on the right rim)
	}
	$slider.children('.SliderWrapCover').css('width',coverWidth);
}

function inputValueChanged(valueMin, valueMax)
{
	updateCounter('CounterMin', valueMin);
	updateCounter('CounterMax', valueMax);
}


// moves the slider to the min or max value of the left/right tip of the sliderWrap is clicked
// this is needed because the graphics of the slider bg is wider than the slider itself..
// that is the user may be clicking to the far right- or left-side but the slider wont
// register a click because the click is on the wrap and not on the slider.
// this function ignores IE6 and IE7 because they calculate the offset of the elements position on the stage wrong
function bindSliderWrapClick($wrapHandle, $slider)
{
	$wrapHandle.click(function(e){
		if ($slider.slider('option', 'disabled'))
		{
			return false;
		}
		// ignore IE6 and IE7 because they calculate offsetLeft wrong
		if(!isIE6() && !isIE7())
		{
			var xClick = e.pageX - this.offsetLeft;
			if(xClick < 200)
			{
				var minValue = $slider.slider('option','min');
				$slider.slider('value',minValue);
			}
			else
			{
				var maxValue = $slider.slider('option','max');
				$slider.slider('value',maxValue);
			}
		}
	});
}

// restricts the input text element to only accept integers as input
function restrictToNumbers($handle)
{
	if($handle.length > 0)
	{
		$handle.keypress(function(event){
			 if( event.which!=8 && event.which!=0 && (event.which<48 || event.which>57))
			 {
				return false;
			 }
		});
	}
}

// restricts the input text element to only accept float numbers
function restrictToFloat($handle)
{
    if($handle.length > 0)
	{
		$handle.keypress(function(event){
		
		    // checks if there is a comma or dot inte the input field, if so do not accept any more commas/dots
            if(event.which==44 || event.which==46)
            {
                if($handle.attr('value').indexOf('.') > -1 || $handle.attr('value').indexOf(',') > -1)
                {
                    return false;
                }
            }
            
            if(event.which!=44 && event.which!=46 && event.which!=8 && event.which!=0 && (event.which<48 || event.which>57))
            {
                return false;
            }
		});
	}
}


// --------------------------------------------
//		Counter
// --------------------------------------------

function initCounters()
{
	if(!$.browser.msie)
		$('.Counter img:not(:.Active)').css('opacity',0.4);
}

function enableCounters()
{
	$('.CounterHolderCover').css('opacity',0);
}

function disableCounters()
{
	$('.CounterHolderCover').css('opacity',0.5);
}

//updateCounter('CounterMax',55559318472);
//updateCounter('CounterMin',84792);

// sets the value on the counter
// accepts an integer which has a maxiumum of 8 characters
// if more than 8 characters are submitted the overflow is truncated counting from the right side
// example:
// updateCounter(9318472777);
// will set this value on the counter: 18472777
function updateCounter(counterID, value)
{
	enableCounters();
	var strValue = value.toString();
	var arrValues = strValue.split('');
	var numChars = arrValues.length;
	var cnt = 1;
	// go trough the indexes backwards (from highest index to lowest index)
	// only use the 8 first indexes.. break on the 9th
	
	for(var i=numChars; i >= 1; i--)
	{
		if(cnt <= 8)
		{
			counterNum(counterID,cnt,parseInt(arrValues[i-1]));
		}
		else
		{
			break;
		}
		cnt++;
	}
	
	/* Reset left-over numbers */
	var rest = (numChars-8)+9;
	for(var i = rest; i < 9; i++)
	{
		counterNum(counterID,i,0);
	}
}

function counterNum(counterID, base10, value)
{			
	$('#'+counterID+' ._'+base10+' img.Active').removeClass('Active');
	if(!$.browser.msie)
	{
		$('#'+counterID+' ._'+base10+' img').css('opacity',1.0);
	}
	$('#'+counterID+' ._'+base10+' .Revolver').stop().animate({top: '-'+getTop(value)+'px'},(1500),'',function(){counterFadeInactive(counterID, base10);});
	var $activeNum = $('#'+counterID+' ._'+base10+' .Revolver img[alt="'+value+'"]:not(:.Filler)');
	$activeNum.addClass('Active');
}

function counterFadeInactive(counterID, base10)
{
	if(!$.browser.msie)
		$('#'+counterID+' ._'+base10+' img:not(:.Active)').css('opacity',0.4);	
}

function getTop(value)
{
	return (2) + (25 * value);
}

function counterStartLoop(counterID)
{
    enableCounters();
    
    var duration;
    for(var i=1; i <= 8; i++)
    {
        // Duration will get a number between 1100 and 1900, stepping 100; that is 1200, 1300, 1400...1800
        var MinNum=(1); // included
        var MaxNum=(10); // MaxNum is exclusive, that is min: 5 and max: 7, will generate only numbers 5 and 6.. never 7.           
        duration = Math.floor(Math.random()*(MaxNum-MinNum))+MinNum;
        duration *= 100;
        duration += 1000;
        //base10 = i;
        
        startRevolverLoop(counterID, i, duration);
        //$('#'+counterID+' ._'+base10+' .Revolver').animate({top: '-'+getTop(9)+'px'},(duration),'linear',function(){startRevolverLoop(counterID, base10, duration);});
    }
}

// param isRepeating is used by the recursive function which creates a loop
// if set to true it will reset the positions of the numbers when they have reached the end in order to
// make an illusion of a loop.
// When calling this function do not send any value for the last param or send the value false.
function startRevolverLoop(counterID, base10, duration, isRepeating)
{
    if(!$.browser.msie)
	{
		$('#'+counterID+' ._'+base10+' img').css('opacity',1.0);
	}
	
	if(isRepeating)
        $('#'+counterID+' ._'+base10+' .Revolver').css('top','23px');
    $('#'+counterID+' ._'+base10+' .Revolver').animate({top: '-'+getTop(9)+'px'},(duration),'linear',function(){startRevolverLoop(counterID, base10, duration, true)});
}

function counterStopLoop(counterID)
{
    for(var i=1; i <= 8; i++)
    {
        stopRevolver(counterID, i);
    }
}

function stopRevolver(counterID, base10)
{
    $('#'+counterID+' ._'+base10+' .Revolver').stop(true);
}


// --------------------------------------------
//		ToolTip
// --------------------------------------------

var overlayIsOpen = false;
function initToolTip()
{
    $('label.Info').hover(function(){
        if($(this).children('.Msg').css('display') != 'block' && !overlayIsOpen)
        {
            if($.browser.msie)
            {
                $(this).children('.ToolTip').css('display','block');
            }
            else
            {
                $(this).children('.ToolTip').fadeIn('fast');
            }
        }
    },function(){
        if($.browser.msie)
        {
            $(this).children('.ToolTip').css('display','none');
        }
        else
        {
            $(this).children('.ToolTip').fadeOut('fast');
        }
    });
    
    $('label.Info').click(function(){
    
        //alert($(this).parent().attr('nodeName'));
    
        if(isIE6() || isIE7())
        {
            if($('div.Page3').length != 0)
            {
                $thisCol = $(this).parents('div:eq(0)');
                $('.formFields .Col').not($thisCol).css('visibility','hidden');
            }
        }
    
        /*
        $(this).css('position','relative');
        $(this).css('z-index','1003');
        //$(this).css('border','solid 3px red');
    
        //$(this).find('.Msg').css('position','relative');
        $(this).find('.Msg').css('z-index','1003');
        */
        
        
    
    
        if(!overlayIsOpen) // prevent user from clicking on another label.Info element when one element is already open
        {
            $(this).children('.Msg').css('display','block');
            $(this).children('.ToolTip').css('display','none');
            if(!isIE6() && !isIE7())
            {
                $(this).children('.Overlay').css('display','block');
            }
            overlayIsOpen = true;
            $('label.Info').css('cursor','default');
        }
    });
    
    $('label.Info .CloseBtn').click(function(){
    
    
        if(isIE6() || isIE7())
        {
            if($('div.Page3').length != 0)
            {
                //$thisCol = $(this).parents('div:eq(0)');
                //$('.formFields .Col').not($thisCol).css('visibility','hidden');
                $('.formFields .Col').css('visibility','');
            }
        }
    
    
        $(this).parent().parent().parent().css('display','none'); // points at 'span.Msg'
        $(this).parent().parent().parent().parent().children('.Overlay').css('display','none');
        $('label.Info').css('cursor','pointer');
        overlayIsOpen = false;
    });
    
    $('.Header .Right .Label').click(function(){
        //$('.MainContent').css('z-index','90');
        //console.log($('.Header .Right .Label .Msg').css('display'));
        
        if($('.Header .Right .Label .Msg').css('display') ==  'block')
        {
            $('.MainContent').css('z-index','89');
        }
        
    });
    
    $('.Header .Right .Label .Msg .CloseBtn').click(function(){
        //console.log($('.Header .Right .Label .Msg').css('display'));
        
        if($('.Header .Right .Label .Msg').css('display') == 'none')
        {
            $('.MainContent').css('z-index','90');
        }
    });
    
}

//--------------------------------------------
//		DropDown
//--------------------------------------------

function initDropDownHover()
{
	$('.DropDown li a').hover(function(){
	    $(this).parents('ul').find('li a').removeClass('Active'); // removes class active for each "li > a"
	    $(this).addClass('Active');
	},function(){
	    if($(this).parents('.DropDown > ul').hasClass('Over'))
	    {
	        $(this).removeClass('Active');
	    }
	});
}

function removeDropDownHover()
{
	$('.DropDown li a').unbind('hover');	
}

// --------------------------------------------
//		Ajax Loader
// --------------------------------------------

function showAjaxLoader()
{
    showCustomLiteBox();
    $('#CustomLiteBoxElements .CustomLiteBoxWrap .Loader').css('display','block');
    $('#CustomLiteBoxElements .CustomLiteBoxWrap .CustomLiteBox').css('display','none');
}

function hideAjaxLoader()
{
    hideCustomLiteBox();
    $('#CustomLiteBoxElements .CustomLiteBoxWrap .Loader').css('display','none');
    $('#CustomLiteBoxElements .CustomLiteBoxWrap .CustomLiteBox').removeAttr('style');
}

// --------------------------------------------
//		Utils
// --------------------------------------------

function isIE6()
{
	return $.browser.msie && $.browser.version == '6.0';
}

function isIE7()
{
	return $.browser.msie && $.browser.version == '7.0';
}

function isIE8()
{
	return $.browser.msie && $.browser.version == '8.0';
}
