//NOTE: any changes to this file should also be made to actions-new.js and dp.js

// ==ClosureCompiler==
// @output_file_name actions.min.js
// @compilation_level SIMPLE_OPTIMIZATIONS
// ==/ClosureCompiler==

/* Global site actions

VERSION: 2010-04-22

*/

(function ($) {

    //Plug-in definition
    $.fn.extend({

        //Replace each value in array provided with result of the function
        randomiseBrandStory: function(option) {

            // generates a random brand story for inclusion on either the cars footer or portal page
            // extend with customClass to apply custom class
            var defaults = {storyType: 'car'};

            var options = $.extend(defaults, option);
			if (!options.storyType) return;
			
			var storyType = options.storyType.toLowerCase();
			
			var imageFolders = ['dinner-for-3-million/', 'fancy-a-cuppa/', 'meet-asimo/', 'sun-lover/'];
			var imageAlts = ['Dinner for 3 billion', 'Fancy a cuppa?', 'Meet Asimo', 'Sun Lover'];
			
            return this.each(function() {

				if ($(this).length) {

					var random = Math.floor(Math.random() * imageFolders.length);
					var html = ['<img src="'];
					
					//html.push(constants.CDN);
					
					html.push('/_assets/images/brand-stories/');
					html.push(imageFolders[random]);
					
					if (storyType == 'car') {
						//If ie6 then use png8 versions of graphics
						html.push( $.browser.msie && $.browser.version == 6 ? 'car-ie6.png"' :  'car.png"');
					} 
					else {              
						html.push(storyType);
						html.push('.jpg"');
					}
                
                    if (options.customClass) html.push(['" class="', options.customClass, '"'].join(''));

					html.push([' alt="', imageAlts[random], '">'].join(''));

					$(this).append(html.join(''));
				}

                return false;
            });
        }
    });

})(jQuery);


//SESSION COOKIE CODE ************************************************************************************

	function getCookie(c_name)
	{
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
		{ 
		c_start=c_start + c_name.length+1; 
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		} 
	  }
	return "";
	}
	function sessionCookie(c_name)
	{
		cookiestr=getCookie(c_name);
		if (cookiestr==null || cookiestr=="") {
			cookiestr = new Date().getTime()+Math.round(Math.random()*1000000);
			document.cookie=c_name+ "=" +escape(cookiestr);
			document.cookie.path = "/";
		}
		return cookiestr;	//cookie found
	}


//SESSION COOKIE CODE ***********************************************************************************


//DO NOT REMOVE - USED BY FLASH TOP PANEL
 function doFunctions() {

       var funcList      = new Array();
       var func          = new Array();
       var silent        = arguments[0];
       var argsStr       = silent;

       for (var i=1;i<arguments.length;i++) {
              var arg = arguments[i];
              argsStr += ",'" + arg + "'";
              if (arg == "exec") {
                   if (i!=1) funcList.push(func);
                   func = new Array();
              }
              else {
                   func.push(arg);
              }
       }
	   
       funcList.push(func);
       if (!silent) alert("doFunctions(" + argsStr + ")");

       for (var i=0;i<funcList.length;i++) {
             var funcStr = funcList[i][0] + "(";
											  
             if (funcList[i].length > 0) {
                   for (var j=1;j<funcList[i].length;j++) {
                         funcStr += "'" + funcList[i][j] + "',";
                   }
                   if (funcList[i].length>1) funcStr =
 		 		 		 		 		 funcStr.substr(0,funcStr.length-1);
                   funcStr += ")";
                   if (!silent) alert("trying:\n" + funcStr);
                   try {
                         eval(funcStr);
                   }
                   catch(exception) {
                         if (!silent) alert("failed:\n" + exception);
                   }
             }
       }
	}
	


//return querystring parameter
function queryString( name, qString ) {
	var testStr = ( typeof PSEUDOQUERYSTRING == "undefined" ) ? qString : PSEUDOQUERYSTRING;
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( testStr );
	if( results == null )    return "";  else    return results[1];
}
	
function URLDecode(psEncodeString) { var lsRegExp = /\+/g; return unescape(String(psEncodeString).replace(lsRegExp, " ")); }	
	
// TODO: add ajaxLoadAnimation class to common css.

function transform(type,template,service,params,callback) {

	var url = "/_assets/behaviour/transform.asp?type=" + type + "&template=" + escape(template) + "&service=" + escape(service) + "&params=" + escape(params);	
	$.get(url, callback);
}

/**
 * gets the value for a key stored in the global.asa file for the website
 */
function getSetting(key) {
	var value = "";
	$.ajax({"url": "/_assets/behaviour/getglobalvar.asp?var="+key, async: false, success: function(response) {
		value = response.toString();
	}});
	return value;
}

/* tests to see if string is in correct UK style postcode: AL1 1AB, BM1 5YZ etc. */
function isValidPostcode(p) {
	var postcodeRegEx = /[A-Z]{1,2}[0-9R][0-9A-Z]? ?[0-9][A-Z]{2}/i;
	
	/* Regex pre 22/01/09 /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i */

	return postcodeRegEx.test(p);
}

// gets the value of a parameter (strParam) from a href (strHref)
function getQSValue(strParam,strHref)
{
	  strParam = strParam.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+strParam+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( strHref );
	  if( results == null )
		return "";
	  else
		return results[1];
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function FL(id) {		//TO REFER TO THE FLASH OBJECT WITH ID
	if (navigator.appName.indexOf("Microsoft") != -1) {
	   if (window[id]) return window[id];
	   else return false;
	}
	else {
	   if (document[id]) return document[id];
	   else return false;
	}
}
	
	
jQuery.preloadImages = function() {
	var a = (typeof arguments[0] == 'object')? arguments[0] : arguments;
	for(var i = a.length -1; i > 0; i--) {
		jQuery("<img>").attr("src", a[i]);
	}
}

function loadShowroom() {
	$.fn.hondaToolbox.start($("#tools .showroom a"), "link");
}


//INSERT JS FILE FOR TILING AND BG POSITION OF PNGs#
//NB: Moving this code to eg document.ready may cause png fix issues
if ($.browser.msie){ //only IE
	var ver = $.browser.version
	if ((ver >= 5.5) && (ver < 7)){ //only versions that don't support png transparency
		var script = document.createElement('script');
		script.src = '/_assets/presentation/iepngfix_tilebg.js';
		script.type = 'text/javascript';
		document.getElementsByTagName('head').item(0).appendChild(script);
	}		
}

// This is where you set your specific height & width etc... for your popups.
function openPopup(url) {
	window.open(url, 'hondaPopup', 'width=400,height=500,scrollbars,resizable');
	return false;
}

document.write('<link href="/_assets/presentation/javascript-only.css" rel="stylesheet" type="text/css" media="all" />');

$(document).ready(function(){

	// Remove submit button
	$("#search input[type='submit']").remove();
	// Add search image if doesn't exist
	if (!$("#searchBtn").length) $("#search p").append('<a href="#" id="searchBtn" title="Open search field" accesskey="4">Search</a>');
	// Bind behaviour actions to the search query field
	var t;
	$("#q")
		.keyup(function(e){if (e.keyCode == 27) $.closeSearchBox(); })
		.blur(function(){
		   t=setTimeout("$.closeSearchBox()", 2000);
		});
	// Bind behaviour actions to the search button
	$("#searchBtn")
		.focus(function(){clearTimeout(t);})
		.blur(function(){
		   t=setTimeout("$.closeSearchBox()", 2000);
		});
	// Show/hide search box
	$("#searchBtn").click(function(){
		if ($("#q").is(":hidden")) {
			// Add bindings to the search box
			$("#q").show().focus().focus(function(){clearTimeout(t);});
			$("#search p").addClass("open");
			$(this).attr("title", "Search Honda UK");
		} else {
			$("#search").submit();
		}
		return false;
	});
	
	// Pop-up and external links.
	$("a.external").click(function(){
		var url = this.href;
		window.open(url);
		return false;
	});
	
	$("a.help").click(function(){
		var url = this.href;
		openPopup(url);
		return false;
		});

	/*$.getScript("/glossary/_assets/behaviour/jquery.highlight-3-glossary-variant.js", function(){
		runDeptGlossary();
	});*/
	
	// Hide Header & Footer for Digital Platform in a Popup
	if(window.name == "dpPopup") {
		$("#header").hide();
		$("#footer").hide();
		$("#diaryTopContent, #formTopContent, #bookedTopContent").css("margin-top","20px");
	}

	
	// Include tracking/logging scripts asynchronously
	$.ajax({
		url: "/_assets/behaviour/tracking.min.js", 
		type: "GET", 
		dataType: "script",
		cache: true
	});

});

/*function runDeptGlossary() {
}*/

/* Code for highlighting glossary terms 
function glossaryLoad(dataUrl) {
	var $storage = $("body"),json;
	
	if (!($("body#glossaryPage").length > 0)){	// Only do this work on pages that are NOT the Glossary	
		if ($storage.data("glossary")) {
			json = $storage.data("glossary");
			glossaryScan(json);
		} else {
			$.getJSON(dataUrl, function(json) {
				glossaryScan(json);
				$storage.data("glossary", json);
			});
		}
	}
}*/

/*function glossaryScan(json) {
			
	// Find all the terms and wrap them in anchor and definition tags.
	for (i in json.terms) {
		$("#content p").highlight(json.terms[i],json.definitions[i]);
	}*/

	/*// In-Page Glossary, seen when page is printed.
	if (footnoteGlossary.length > 0) {
		var terms = '';
		var footnote = '<div id="footnoteGlossary"><hr/><h2>Glossary</h2><p>Glossary terms used on this page.</p><dl>{terms}</dl></div>';
		var tmpl = '<dt>{term}</dt><dd>{title}</dd>';
	
		for (x in footnoteGlossary) {
			var glossaryPosition = arrayIndexOf(json.terms,footnoteGlossary[x],false); // For given term where is it in the jSON array
			
			// Insert a term and its given definition/description
			terms+= tmpl.replace("{term}", footnoteGlossary[x]).replace("{title}",json.definitions[glossaryPosition]);			
		}
		
		footnote = footnote.replace("{terms}", terms);
		$("#content").append(footnote);
	}*/
/*}*/


jQuery.closeSearchBox = function() {
	$("#q").hide();
	$("#search p").removeClass("open");
	$("#searchBtn").attr("title", "Open search field");
}



function getHttpGetParameters(param, url)
{
	var hrefArray;

	if ( (url != null) && (url != "") )
	{
		// split the URL at the ? character
		hrefArray = url.split('?');
	}
	else
	{
		// split the URL at the ? character
		hrefArray = document.location.href.split('?');
	}

	// if the split produces only 1 array element then return an error
	if (hrefArray.length == 1)
	{
		return '';
	}

	var queryString = hrefArray[1].split('#'); // We don't want any hash.

	// split the 2nd part of the array at the & character
	var parameterPairs = queryString[0].split('&');
	var parameterValues = '';

	// iterate over the pairings (param1=a,param2=b)
	for (var pair in parameterPairs)
	{
		// get the param and value into array
		var bits = parameterPairs[pair].split('=');

		// if the param equals our chosen param, then add it to the list
		if (bits[0] == param)
		{
			parameterValues += bits[1] + ',';
		}
	}  

	return parameterValues.substring(0, parameterValues.length-1).split(',');
}    

function getDateSuffix(date) {
	if ( (date == 1) || (date == 21) || (date == 31) ) {
		return "st";
	}
	if ( (date == 2) || (date == 22) ) {
		return "nd";		
	}
	if ( (date == 3) || (date == 23) ) {
		return "rd";
	}
	return "th";
}

function convertEscapedCharacters(value) {
	var pos = value.indexOf("%");
	while (pos != -1) {
		var hex = value.substring(pos+1, pos+3);
		if (!hex.match("\d*")) {
			pos = value.indexOf("%", pos+1);
			continue;
		}
		var character = String.fromCharCode(parseInt(hex,16))
		value = value.substring(0, pos) + character + value.substring(pos+3, value.length);
		pos = value.indexOf("%", pos+1);
	}

	return value.toString();
}

// Thickbox
$.ajax({url:"/_assets/behaviour/jquery.thickbox-compressed.js", type:"GET", dataType:"script", cache:true});

//HONDA TV redirect based on broswer
$(document).ready(function(){
	if ($.browser.msie){ //browser is IE
		var jhref = "http://tv.honda.co.uk?keepThis=true&TB_iframe=true&height=380&width=680";
	}else{ //browser is not IE
		var jhref = "http://tv.honda.co.uk?keepThis=true&TB_iframe=true&height=380&width=680";
	}	
	
	$('#hondaTvURL').attr('href',jhref); 
	
	$("#siteJump").submit(function(){
		var theForm = $(this).get(0);
		if (theForm.menu.selectedIndex>0) window.open(theForm.menu.options[theForm.menu.selectedIndex].value);
		return false;
	});
});



function arrayIndexOf(searchArray,searchTerm,caseSensitive) {
	if(caseSensitive) {
		for(arrayCount = 0; arrayCount < searchArray.length; arrayCount++) {
			if(searchArray[arrayCount] == searchTerm) {
				return arrayCount;
			}
		}
	} else {
		for(arrayCount = 0; arrayCount < searchArray.length; arrayCount++) {
			if(searchArray[arrayCount].toUpperCase() == searchTerm.toUpperCase()) {
				return arrayCount;
			}
		}
	}
	return -1;
}






