// Simple jQuery cookie settting/getting function
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined'  ||  (name  &&  typeof name != 'string')) { // name and value given, set cookie
        if (typeof name == 'string') {
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = name + '=' + encodeURIComponent(value) + expires + path + domain + secure;
        } else { // `name` is really an object of multiple cookies to be set.
          for (var n in name) { jQuery.cookie(n, name[n], value||options); }
        }
    } else { // get cookie (or all cookies if name is not provided)
        var returnValue = {};
        if (document.cookie) {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (!name) {
                    var nameLength = cookie.indexOf('=');
                    returnValue[ cookie.substr(0, nameLength)] = decodeURIComponent(cookie.substr(nameLength+1));
                } else if (cookie.substr(0, name.length + 1) == (name + '=')) {
                    returnValue = decodeURIComponent(cookie.substr(name.length + 1));
                    break;
                }
            }
        }
        return returnValue;
    }
};


function updateLocationCookieFromBreadcrumb(loc) {
	r = $('#breadcrumbcountryselect > form > acronym:first-child > select').val().split('.');
	$.cookie({'region':r[0],'country':r[1]},{expires:180,path:'/'});
	
	if (loc)
		window.location = loc.replace(/\/[a-zA-Z][a-zA-Z]\//,'/'+r[1]+'/');
	else
		window.location = window.location.href.replace(/\/[a-zA-Z][a-zA-Z]\//,'/'+r[1]+'/');
}

function updateLanguageCookieFromBreadcrumb() {
	r = $('#breadcrumbcountryselect > form > acronym:last-child > select').val();
	$.cookie({'language':r},{expires:180,path:'/'});
	
	window.location = window.location;
}


$().ready(function() {

	// Test that the users browser will accept cookies
	$.cookie({'testsettings':'1'},{expires:180,path:'/'});
	var timeout = (new Date()).getTime()+8000;
	var navDone = false;
	
	/*
	 * These two functions combine to act as a timeout for when to display manual
	 * country selection when the user does not notice the geolocation prompt
	 */
	function checkTimeout() { return ((new Date()).getTime() >= timeout) }
	
	function runTimeoutCheck() {
		if (checkTimeout())
			failedLocate();
		else
			setTimeout(runTimeoutCheck,250);
	}

	/*
	 * Attempt to Geolocate the user
	 * 1. User brower based location to locate coordinates
	 * 2. Reverse geocode those coordinates via google maps api
	 * 3. Break out basic information (zipcode, country) from results
	 * 4. Ajax query to determine the appropriate language to set based
	 *	  on the database as well as browser language preferences
	 * 5. If successful set all cookies and refresh the page
	 *
	 * Any steps that fail will exit the process and run failedLocate
	 */
	var p = 1;
	if (!(($.cookie('region').length > 1) && ($.cookie('country').length > 1) && ($.cookie('language').length > 1))) {
		if ($.cookie('testsettings') == '1' && navigator.geolocation) {
			var geo = new google.maps.Geocoder();
			setTimeout(runTimeoutCheck,250);
			$.colorbox({height:'150px',inline:true,href:'#configuresite',transition:"none",overlayClose:false,escKey:false,close:"",onCleanup:function() { $.cookie({'country':'us','language':'eng'},{expires:180,path:'/'}); window.location = window.location; }});
			navigator.geolocation.getCurrentPosition(
				function success(e) {
					if (navDone) return;
					navDone = true;
					var country = null;
					var zipcode = null;
					timeout += 3000;
					var a = geo.geocode({'latLng':new google.maps.LatLng(e.coords.latitude,e.coords.longitude)}, function(results,status) {
						if (status == google.maps.GeocoderStatus.OK) {
							for (i in results[0].address_components) {
								if ($.inArray('country',results[0].address_components[i].types) > -1)
									country = results[0].address_components[i].short_name;
								if ($.inArray('postal_code',results[0].address_components[i].types) > -1)
									zipcode = results[0].address_components[i].short_name;
							}
							if (country != null) {
								timeout += 1000;
								var domain = (document.domain.match('rts') > -1) ? document.domain : document.domain+'/site';
								$.ajax({
									url: 'http://'+domain+'/jxGetLanguage.php',
									data: 'c='+country,
									dataType: 'xml',
									success: function(d,s,x) {
										if ($(d).find('language').eq(0).text() != -1) {
											$.cookie({'country':country,'language':$(d).find('language').eq(0).text(),'lat':e.coords.latitude,'lng':e.coords.longitude},{expires:180,path:'/'});
											if (zipcode != null)
												$.cookie({'zip':zipcode},{expires:180,path:'/'});
											window.location = window.location;
										} else {
											// Failed to get language from the header or country
											//try { console.log("Failed to get language from the header or country"); } catch (err) { }
											failedLocate();
										}
									},
									error: function(x,s,t) {
										// Failed to get country code from database
										//try { console.log("Failed to get country code from database"); } catch (err) { }
										failedLocate();
									}
								});
							} else {
								// Failed to find the country from the coordinates
								//try { console.log("Failed to find the country from the coordinates"); } catch (err) { }
								failedLocate();
							}
						} else {
							// Failed to reverse geolocate the country
							//try { console.log("Failed to reverse geolocate the country"); } catch (err) { }
							failedLocate();
						}
					});
				},function failure(e) { /* Broweser failed to geolocate try { console.log("Broweser failed to geolocate");  } catch (err) { } */ failedLocate(); });
		} else {
			// Can not use browser geolocation
			//try { console.log("Can not use browser geolocation"); } catch (err) { }
			failedLocate();
		}
	}

	// Gelocation has failed for one of various reasons, prompt with the manual country select UI
	function failedLocate() {
		if ($.cookie('testsettings') == '1' && (!($.cookie('region').length > 1) || !($.cookie('country').length > 1) || !($.cookie('language').length > 1))) {
			// Style fix for IE browsers
			$('#regionselectdisplay ul:last-child').css({border:'0px'});
		
			// Region selection prompt
			$('#countrycookie').attr('checked','checked');
			$('#regionselectdisplay ul .rsl').css('visibility','hidden');
			
			$.colorbox({width:'90%',height:'90%',inline:true,href:'#regionselectdisplay',transition:"none",overlayClose:false,escKey:false,close:"<span style='font-size:5pt; position:relative; left:-22px; top:2px'>View Global Site</span>",onCleanup:function() { $.cookie({'country':'us','language':'eng'},{expires:180,path:'/'}); window.location = window.location; }});
			$('#cboxClose').css({'top':'auto','bottom':'0px'});
			
			$('#regionselectdisplay ul .rsc a').bind('click',function(e) {
				e.preventDefault();
				var r = $(this).attr('rel').split('.');
				$.cookie({'region':r[0],'country':r[1],'language':r[2]},{expires:180,path:'/'});
				window.location = window.location;
				$.colorbox.close();
			});
			
			$('.regionheader').bind('click',function() {
				$('.regionheader').siblings('ul').not('ul:last-child').css('display','none');
				$(this).siblings('ul').css('display','block');
			});
		} else {
			// If this is not already set in the url forward
			if (!dnrf) {					
				if (window.location.toString().search(/\?/) == -1)
					window.location = window.location+'?country=US';
				else
					window.location = window.location+'&country=US';
			}
		}
	}


	// Set Youtube Players to 16:9 alignment if possible
	$('.youtube-player').each(function() { $(this).css({'height':30+(9*($(this).width()/1))/16}) });

	// Align language cookie with the language dropdown after and country change
	r = $('#breadcrumbcountryselect > form > select:last-child').val();
	$.cookie({'language':r},{expires:180,path:'/'});

	// Hook events for equipment list tooltips	
	$('.equiptip').mouseenter(function() {
		clearTimeout($('.equiptip').data('clearcheck'));
		$(this).addClass('equipTop');
		$('#equipboxcontent').html($("#"+$(this).find('a').attr('rel')).html());
		$('#equipbox').css('display','block');
		$('#equipboxwhitebox').css('display','block');
		$('#equipboxwhitebox').width(Math.round($(this).width()+2));
		$('#equipbox').height($('#equipboxcontent').height());
		var offT = $(this).offset().top + $(this).height() + 2;
		var offL = Math.round($(this).offset().left + ($(this).width() / 2) - ($('#equipbox').width() / 2));
		$('#equipbox').offset({top:offT,left:offL});
		$('#equipboxwhitebox').offset({left:Math.round($(this).offset().left+2)});
	});
	$('.equiptip').mouseleave(function() {
		var tipsrc = $(this);
		var timeoutId = setTimeout(function() { $('#equipbox').css('display','none'); $(tipsrc).removeClass('equipTop'); },500);
		$(this).data('clearcheck',timeoutId);
	});
	$('.equiptip').bind('click',function(e) { e.preventDefault(); });
	$('#equipbox').mouseenter(function() { $('.equiptip').each(function() { clearTimeout($(this).data('clearcheck')); }); });
	$('#equipbox').mouseleave(function() { $('#equipbox').css('display','none'); $('.equiptip').removeClass('equipTop'); });


	// Hook events for social media share tooltips			
	$('.sharetip').mouseenter(function() {
		clearTimeout($('.sharetip').data('clearcheck'));
		$(this).addClass('sharetipTop');
		if ($(this).children('a').attr('rel').search('telex.com') > -1)
			var l = $(this).children('a').attr('rel');
		else if ($(this).children('a').attr('rel').search(/http/i) > -1)
			var l = $(this).children('a').attr('rel');
		else
			var l = window.location.href.substr(0,window.location.href.lastIndexOf('/')+1) + $(this).children('a').attr('rel');
		$('#fbsharetip').attr('href','http://www.facebook.com/share.php?u='+l);
		$('#lisharetip').attr('href','http://www.linkedin.com/shareArticle?mini=true&amp;url='+l+'&amp;source=http://www.telex.com');
		$('#twsharetip').attr('href','http://twitter.com/home?status='+l);
		$('#emsharetip').attr('href','mailto:?subject=Shared from the Telex.com Website&body='+l);
		$('#sharetipbox').css('display','block');
		$('#sharetipboxwhitebox').css('display','block');
		$('#sharetipboxwhitebox').width(Math.round($(this).width()+2));
		var offT = $(this).offset().top + $(this).height() + 2;
		var offL = Math.round($(this).offset().left + ($(this).width() / 2) - ($('#sharetipbox').width() / 2));
		$('#sharetipbox').offset({top:offT,left:offL});
		$('#sharetipboxwhitebox').offset({left:Math.round($(this).offset().left+2)});
	});
	$('.sharetip').mouseleave(function() {
		var tipsrc = $(this);
		var timeoutId = setTimeout(function() { $('#sharetipbox').css('display','none'); $(tipsrc).removeClass('sharetipTop'); },500);
		$(this).data('clearcheck',timeoutId);
	});
	$('.sharetip').bind('click',function(e) { e.preventDefault(); });
	$('#sharetipbox').mouseenter(function() { $('.sharetip').each(function() { clearTimeout($(this).data('clearcheck')); }); });
	$('#sharetipbox').mouseleave(function() { $('#sharetipbox').css('display','none'); $('.sharetip').removeClass('sharetipTop'); });


	// Hook events for contact form defaults control
	$(".mainContactFormBox input,.mainContactFormBox textarea,.accountPage input").each(function() {
		if ($(this).attr("type") != "button" && $(this).attr("type") != "submit") {
			var initValue = $(this).val();
			$(this).bind("focus",function() {
				if ($(this).val() == initValue)
					$(this).val("");
			});
			$(this).bind("blur",function() {
				if ($(this).val() == "")
					$(this).val(initValue);
			});
		}
	});


	// Parse out simple obfuscation of email addresses
	$('.edcd').each(function() {
		$(this).html($(this).html().replace(/{AT}/g,'@').replace(/{DOT}/g,'.'));
		$(this).attr('href','mailto:'+$(this).html());
	});

});



