/*
	file: /etc/designs/cen/js
	
	desc: This will be a gloabl script for in house javascript utils functions that will get use over the website
	
	Changelog:
		9/13/2011: added the getCookie function (yong qui zheng) 
*/

	/*
		get the cookie of the current page
		@cookieIngredient: is the name of the cookie
	*/
	$(document).ready(function(){
		//ie7 fixed article page
		if($.browser.msie){
			if($.browser.version=="7.0"){
				
				//a fixed for ie issue with the multistory float left problem
				if($("#multistory_box_left").length >0){
					//when this element exist
					var mulBoxLeft=$("#multistory_box_left").html();
					$("div#article_text div.parsys").first().prepend("<div id='multistory_box_left'>"+mulBoxLeft+"</div>");
					$("#multistory_box_left").remove();
				}
				$(".articlemedia .floatRight").parent().addClass("ie7right");
			}
		}
		
		//Reset selected when the back button is pressed
		$("select").each(function() {
			var index = 0;
			$(this).find("option").each(function(i) {
				if (this.defaultSelected === true)
				{
					//compatibility?
					this.selected = true; 
					$(this).attr("selected", "selected");
				}
			});
		});
	});
	
	function findEnclosedRegions(map)
	{
		var regions = new Array();
		var numOpen = 0;
		var startIndex = 0;
		for (var i = 0; i < map.length; i++)
		{
			var c = map.charAt(i);
			if (c === '[')
			{
				if (numOpen === 0)
				{
					startIndex = i;
				}
				numOpen++;
			}
			else if (c === ']')
			{
				if (numOpen > 0)
				{
					numOpen--;
				}
				if (numOpen === 0)
				{
					var endIndex = i;
					regions.push({ "startIndex": startIndex, "endIndex": endIndex+1, "value": map.substring(startIndex+1, endIndex) });
				}
			}
		}
		return regions;
	}
	
	function getJSONVariable(node, name)
	{
		if (typeof node[name] === "undefined")
		{
			throw ("JSON key [" + name + "] not found in function getJSONVariable.");
		}
		return node[name];
	}
	
	/**
	* Takes a json node, and a map string with references to keys in the json node
	* Replaces the references with the value from the json node
	* The references should be enclosed in square brackets.
	* Example:
	* var node = { 'key': 'value' };
	* mapJSON(node, 'i wish my key was a [key]') -> "i wish my key was a value"
	* Also works with conditional insertion of text.
	* Example:
	* var node = { 'numberKey': 2 }
	* mapJSON(node, 'is JSON great? [[numberKey] > 1 ? "yes"]') -> "is JSON great? yes"
	* @author Patrick Armstrong
	*/
	function mapJSON(node, map, /*boolean*/isPubMode)
	{
		var enclosedRegions = findEnclosedRegions(map);
		var eqPattern = /^\s*(\[?\w+\]?)\s*(>|<|>=|<=|==)\s*(\[?\w+\]?)\s*$/;
		var varPattern = /\[(\w+)\]/;
		var stringPattern = /(["'])([^\1]*)\1/;
		var operandPattern = /^\d+$/;
		var arrMatch = null;
		var string = "";
		var lastMatchIndex = 0;
		for (var i = 0; i < enclosedRegions.length; i++)
		{
			string += map.substring(lastMatchIndex, enclosedRegions[i].startIndex);
			var match = enclosedRegions[i].value;
			if (match.indexOf("?") !== -1)
			{
				var split = match.split("?");
				if (eqPattern.test(split[0]))
				{
					var eqMatch = eqPattern.exec(split[0]);
					var operand1 = eqMatch[1];
					var operator = eqMatch[2];
					var operand2 = eqMatch[3];
					if (varPattern.test(operand1))
					{
						operand1 = getJSONVariable(node, varPattern.exec(operand1)[1]);
					}
					if (varPattern.test(operand2))
					{
						operand2 = getJSONVariable(node, varPattern.exec(operand2)[1]);
					}
					var result = false;
					if (operandPattern.test(operand1) && operandPattern.test(operand2))
					{
						if (operator === ">")
						{
							result = operand1 > operand2;
						}
						else if (operator === "<")
						{
							result = operand1 < operand2;
						}
						else if (operator === ">=")
						{
							result = operand1 >= operand2;
						}
						else if (operator === "<=")
						{
							result = operand1 <= operand2;
						}
						else if (operator === "==")
						{
							result = operand1 == operand2;
						}
						if (result)
						{
							var insert = $.trim(split[1]);
							if (varPattern.test(insert))
							{
								string += getJSONVariable(node, varPattern.exec(insert)[1]);
							}
							else if (stringPattern.test(insert))
							{
								string += stringPattern.exec(insert)[2];
							}
							else
							{
								string += split[1];
							}
						}
					}
				}
			}
			else
			{
				string += getJSONVariable(node, $.trim(match));
			}
			lastMatchIndex = enclosedRegions[i].endIndex;
		}
		string += map.substring(lastMatchIndex);
		if( isPubMode === true ) {
			// /content/cen/articles/89/i43/BryostatinsTale.html -->
			// /articles/89/i43/BryostatinsTale.html
            string = string.replace("/content/cen", "");
        }
		return string;
	}
	
	function getCookie(cookieIngredient){
		var cookieDough=document.cookie.split(";");
		var chocolateChipCookie=[];
		var chocolate,chip;
		for(var i=0; i<cookieDough.length;i++){
			chocolate=cookieDough[i].substr(0,cookieDough[i].indexOf("="));
			chip=cookieDough[i].substr(cookieDough[i].indexOf("=")+1);
			chocolate=chocolate.replace(/^\s+|\s+$/g,"");
			if(cookieIngredient!=null && cookieIngredient!=""){
				if(chocolate==cookieIngredient){
					return chip;
				}
			}else{
				chocolateChipCookie.push({chocolate:chip});
			}
		}
		return chocolateChipCookie;
	}
	
	function getOffscreenImageDimensions(url)
	{
		var dimensions = {};
		var temp = loadImage(url);
		dimensions.width = temp.find("img").width();
		dimensions.height = temp.find("img").height();
		removeLoadedImages();
		return dimensions;
	}
	
	function loadImage(url)
	{
		var temp = $("<div class='hide-me'></div>");
		temp.html("<img src='"+url+"' />");
		$("body").append(temp);
		return temp;
	}
	
	function removeLoadedImages()
	{
		$("body div.hide-me").remove();
	}
