var documentHeight = "";
jQuery(document).ready(function () {
//calculateTopPageShorcutHeight();
//topPageShortcutHackForAdjustFontSizeJS ();

calculateTopPageFeaturedArticleHeight();
topPageFeaturedArticleHackForAdjustFontSizeJS ();

//window.setTimeout ("usePNGBorders()", 500);


    jQuery('.NewsTicker').cycle({
        fx:     'scrollVert',
        next:   '#btnDown',
		prev:   '#btnUp'
    });
	// If only one li in newsticker, hide the top/down buttons
	 if (jQuery('.NewsTicker li').length ==1){jQuery('.NewsTickerBtns').css('display','none');}
	
	 jQuery('.NewsTicker').mouseout(function (){
		jQuery (this).cycle("resume");
	 });

	jQuery('.NewsTicker').mouseover(function (){
		jQuery (this).cycle("pause");
	 });
	//-- edit on 19 dec
	jQuery ('.NewsTicker li').css ('visibility', 'visible');

	//commenetd by mahendar 
	/*jQuery("input[id='email']").blur( function () {
		var bool;
		var $errorMsg;
		bool = verifyEmail( jQuery(this).val());

		$errorMsg = jQuery(this).parent().find (".error");
		if (!bool){
			$errorMsg.css('display', 'block');
		}
		else{
			$errorMsg.css('display', 'none');
		}

	});*/

	// Added by mahedar for Enewslettr Button Email validation

	/*jQuery("div#enewsletterEmail").click( function (){
	
	    var bool;
		var $errorMsg;
		bool = verifyEmail( jQuery("input[id='email']").val());

		$errorMsg =  jQuery("div#errorEnewslettEmail");
		if (!bool){
			$errorMsg.css('display', 'block');
			return false;
		}
		else{
			$errorMsg.css('display', 'none');
			var eNewsletter=document.getElementById('eNewsletter');
			if(eNewsletter!=null)
			{
			alert(eNewsletter);
			eNewsletter.submit();
			}
		}	

	});*/

	jQuery("input[id='email']").focus(clearField);

	calcColumnHeightTop();
	
	// RYAN QUIOGUE
	if(jQuery('#greyBox').length != -1){
		var divHeightMax = Math.max(jQuery('#greyBox .whereToBuyDiv').height(),jQuery('#greyBox .supportTempDiv').height());
		jQuery('#greyBox .whereToBuyDiv, #greyBox .supportTempDiv').height(divHeightMax);
	}
});


function clearField (){
	jQuery(this).val ("");
	jQuery(this).unbind ("focus");
}


function changeBG(pathToImage, cssRules){

	var undefinedVar;
	var backgroundCss;
	var undefinedVar;
	var $body;
	if (documentHeight == "")
		documentHeight = $jq(document).height();
	$body = jQuery('#BaseBgDiv');

	if ((pathToImage != undefinedVar && pathToImage != "" && pathToImage != null && pathToImage != 'null') && (pathToImage != "" && pathToImage != null && pathToImage != undefinedVar && pathToImage != 'null')){
		//usePNGBorders()
		cssRules		= (cssRules != undefinedVar && cssRules != "")? cssRules : "";
		backgroundCss	= "url(" + pathToImage + ") " + cssRules;
		$body.css('background', backgroundCss);
		if (!$jq.browser.msie)
			$body.css('height',documentHeight);
	}
	else{

		$body.css('background', 'transparent');
		//$body.css('background-repeat', 'repeat-x');
		//$body.css('background-position', 'top left');
	}
	$body.fadeIn (400);

}

function usePNGBorders (){
	var $baseBg = jQuery('.basebg');
	$baseBg.css('background-image', '');
	$baseBg.css('background-image', 'url(/HP/images/top_page/bg/base_bg2.png)');
	$baseBg.css('background-repeat', 'repeat-y');
	$baseBg.css('background-position', 'top left');
	$baseBg.css('hasLayout', true);


	var $pageLeft =jQuery('.pageleft');
	$pageLeft.css('background', 'transparent');


	var $pageRight = jQuery('.pageright');
	$pageRight.css('background', 'transparent');

	var $topShadow =jQuery('.pagetopshadow');
	var $btmShadow =jQuery('.pagebotshadow');
	$topShadow.css('background-image', 'url(/HP/images/top_page/bg/pg_top_grnt2.png)');
	$btmShadow.css('background-image', 'url(/HP/images/top_page/bg/pg_bot_grnt2.png)');
}

/***********************************************/
/* Start :  support shortcut footer hack         */

function topPageShortcutHackForAdjustFontSizeJS (){

	jQuery('.adjusticonpanel').find('a').each(function(){
		var defaultfunctions;
		var updatedfunctions;
		defaultfunctions	= jQuery(this).attr('onclick');

		if (jQuery.browser.msie){
			defaultfunctions	= getFunctionContents (defaultfunctions);
			updatedfunctions	= "window.setTimeout ('calculateSupportTopPageHeight()', 200);" + defaultfunctions ;
			updatedfunctions	= new Function (updatedfunctions);
			this.onclick		= updatedfunctions;

		}
		else{
			updatedfunctions	= "window.setTimeout ('calculateTopPageShorcutHeight()', 200);"+ " " + defaultfunctions ;
			jQuery(this).attr('onclick', updatedfunctions);
		}
	});
}



function calculateTopPageShorcutHeight(){
	var total;
	var i;
	var maxHeight;
	var domObj;
	var $centerFooterFeat = jQuery('.CenterFooterFeat');
	var $instance;
	total	= $centerFooterFeat.length
	for (i = 0; i < total; ++i){
		domObj 		= $centerFooterFeat[i];
		$instance	= jQuery(domObj);
		$instance.css ('height', 'auto'	);
		if (maxHeight == null){
			maxHeight = $instance.height();
		}
		else{
			if ($instance.height() > maxHeight)
				maxHeight = $instance.height();
		}
	}

	$centerFooterFeat.css ('height', maxHeight + 22);
	jQuery('.CenterFooter .greyfootertop').css ('height', maxHeight + 37);
	jQuery('.CenterFooter .greyfooterbtm').css ('height', maxHeight + 37);
}


/***********************************************/
/* Start :  featured articles height hack         */

function topPageFeaturedArticleHackForAdjustFontSizeJS (){

	jQuery('.adjusticonpanel').find('a').each(function(){
		var defaultfunctions;
		var updatedfunctions;
		defaultfunctions	= jQuery(this).attr('onclick');

		if (jQuery.browser.msie){
			defaultfunctions	= getFunctionContents (defaultfunctions);
			updatedfunctions	= "window.setTimeout ('calculateTopPageFeaturedArticleHeight()', 200);" + defaultfunctions ;
			updatedfunctions	= new Function (updatedfunctions);
			this.onclick		= updatedfunctions;

		}
		else{
			updatedfunctions	= "window.setTimeout ('calculateTopPageFeaturedArticleHeight()', 200);"+ " " + defaultfunctions ;
			jQuery(this).attr('onclick', updatedfunctions);
		}
	});
}




function calculateTopPageFeaturedArticleHeight(){/*
	var total;
	var i;
	var maxHeight;
	var domObj;
	var undefinedVar
	var instanceHeight;
	var $centerFeature;
	$centerFeature	= jQuery('.CenterFeature');
	total	= $centerFeature.length
	for (i = 0; i < total; ++i){
		domObj = $centerFeature[i];
		instanceHeight = jQuery(domObj).height();
		if (maxHeight == undefinedVar){
			maxHeight = instanceHeight
		}
		else if (instanceHeight > maxHeight){
				maxHeight = instanceHeight;
		}
	}

	jQuery('.CenterFeatures').css ('height', maxHeight);*/
}
// Image Preloader - http://www.innovatingtomorrow.net/2008/04/30/preloading-content-jquery
jQuery.preloadImages = function(arguments){
  for(var i = 0; i<arguments.length; i++){
    jQuery("<img>").attr("src", arguments[i]);
  }
}


	function verifyEmail(email){
		//List of known top-level domains that an e-mail address must end with.
		var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

		//The following string represents an atom (basically a series of non-special characters)
		var atom = "\[^\\s" + "\\(\\)><@,;:\\\\\\\"\\.\\[\\]" + "\]" + '+';

		//The following string represents one word in the typical username.
		var word = "(" + atom + "|" + "(\"[^\"]*\")" + ")";

		// The following pattern describes the structure of the user
		var userPattern = new RegExp("^" + word + "(\\." + word + ")*$");

		//The following pattern describes the structure of a normal symbolic domain.
	//  , as opposed to ipDomainPat, shown above.
		var domainPatttern = new RegExp("^" + atom + "(\\." + atom +")*$");

		//Break up user@domain.
		var matchArray = email.match(/^(.+)@(.+)$/);

		//Address doesn't fit the general format of a valid e-mail address. eg. user@domain.com
		if (matchArray == null)
			return false;

		var user = matchArray[1];
		var domain = matchArray[2];

		// Start by checking that only basic ASCII characters are in the strings (0-127).
		for (i=0; i<user.length; i++) {
			if (user.charCodeAt(i)>127 || domain.charCodeAt(i)>127)
				return false;
		}

		//Check if "user" is valid
		if (user.match(userPattern)==null)
			return false;

		//Check if "domain" is valid.
		var atomPattern = new RegExp("^" + atom + "$");
		var domArray = domain.split(".");
		var domArrayLen = domArray.length;
		for (i=0 ; i<domArrayLen ; i++) {
			if (domArray[i].search(atomPattern)==-1)
				return false;
		}

		//Check to confirm domain name ends in a known top-level domain or a two-letter word representing country.
		if (domArray[domArray.length-1].length!=2 && domArray[domArray.length-1].search(knownDomsPat)==-1)
			return false;

		// Make sure there's a host name preceding the domain.
		if (domArrayLen<2)
			return false;

		return true;
	}







/**
 * Column Auto Resize
 **/
/***********************************************/
/* Start :  Three Column Height Hack (Modified by Dinu - Simillar function Line 543 downards)     */

function calcColumnHeightForAdjustFontSizeJS2 (){

	$jq('.adjusticonpanel').find('a').each(function(){
		var defaultfunctions;
		var updatedfunctions;
		defaultfunctions	= $jq(this).attr('onclick');

		if ($jq.browser.msie){
			defaultfunctions	= getFunctionContents (defaultfunctions);
			updatedfunctions	= "window.setTimeout ('reCalcHeight()', 200);" + defaultfunctions ;
			updatedfunctions	= new Function (updatedfunctions);
			this.onclick		= updatedfunctions;

		}else{
			updatedfunctions	= "window.setTimeout ('reCalcHeight()', 200);"+ " " + defaultfunctions ;
			$jq(this).attr('onclick', updatedfunctions);
		}
	});
}

// Adjuster Function
function calcColumnHeight2(el){
	var total;
	var i;
	var maxHeight = 0;
	var domObj;
	total	= $jq(el).length;
	for (i = 0; i < total; ++i){
		domObj = $jq(el)[i];
		$jq(domObj).css ('height', 'auto'	);
		if (maxHeight == null){
			maxHeight = $jq(domObj).height();
		}
		else{
			if ($jq(domObj).height() > maxHeight)
				maxHeight = $jq(domObj).height();
		}
	}
	$jq('.threecolumn .seperator').css ('height', maxHeight);


}

// Wrapper Functions
function calcColumnHeightTop()  { //featureBackground();
	calcColumnHeight2('.threecolumn .column');calcColumnHeightForAdjustFontSizeJS2();}
function calcColumnHeightBot()  { calcColumnHeight2('.threecolumn .column');}
function reCalcHeight()         { calcColumnHeight2('.threecolumn .column');}

// Pluggable Column Backgrounds
function featureBackground(){
	var len = $jq('.threecolumn .column').length;

	switch (len) {

		case 2:
			$jq('.threecolumn .column:eq(0)').addClass('shadowed');
			$jq('.threecolumn .column:eq(1)').addClass('secondColumn');
			break;
		case 3:
			$jq('.threecolumn .column:eq(0)').addClass('shadowed');
			$jq('.threecolumn .column:eq(1)').addClass('shadowed');
			$jq('.threecolumn .column:eq(1)').addClass('secondColumn');
			$jq('.threecolumn .column:eq(2)').addClass('thirdColumn');
	}
}

function footerBackground(){
	var len = $jq('#suppshortcut .shortcutcontent').length;

	switch (len) {

		case 2:
			$jq('#suppshortcut .shortcutcontent:eq(0)').addClass('divide');
			break;
		case 3:
			$jq('#suppshortcut .shortcutcontent:eq(0)').addClass('divide');
			$jq('#suppshortcut .shortcutcontent:eq(1)').addClass('divide');
	}

	// Check if there is an image in the support section

	// First Item
	if ($jq('#suppshortcut .shortcutcontent:eq(0) img').length > 0){
		$jq('#suppshortcut .shortcutcontent:eq(0) .shortcutcontentBody').addClass('hasImage');
	}

	// Second Item
	if ($jq('#suppshortcut .shortcutcontent:eq(1) img').length > 0){
		$jq('#suppshortcut .shortcutcontent:eq(1) .shortcutcontentBody').addClass('hasImage');
	}

	// Third Item
	if ($jq('#suppshortcut .shortcutcontent:eq(2) img').length > 0){
		$jq('#suppshortcut .shortcutcontent:eq(2) .shortcutcontentBody').addClass('hasImage');
	}

}


/* Load Events */
addLoadEvent (calcColumnHeightTop);
//addLoadEvent (footerBackground);

function eNewsletterSubmit()
{     
        var bool;
		var $errorMsg;
		bool = verifyEmail( jQuery("input[id='email']").val());

		$errorMsg =  jQuery("div#errorEnewslettEmail");
		if (!bool){
		    
		    var errorText=document.getElementById('errorText');
		   		   
		    var errorEnewslettEmail=document.getElementById('errorEnewslettEmail');
		    
               if(errorEnewslettEmail!=null && errorText!=null){
                         errorEnewslettEmail.innerHTML=errorText.innerHTML;
                     }

			$errorMsg.css('display', 'block');
			
		}
		else{
			$errorMsg.css('display', 'none');
			var eNewsletter=document.getElementById('eNewsletter');
			var url='';
			if(eNewsletter!=null)
			url=eNewsletter.action;
			//alert(url);
			newLatterXmlhttpPost(url,eNewsletter,'span') 
			trackHomeElement(this, 'Home.eNewsletter');
			
			}
			
}

function newLatterXmlhttpPost(strURL,formName,span) 
{
 	var xmlHttpReq = false;
    var self = this;

    if (window.XMLHttpRequest) 
    {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) 
    {
		self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    self.xmlHttpReq.open('POST', strURL, true);
	self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	
	self.xmlHttpReq.onreadystatechange = function() 
	{
	    if (self.xmlHttpReq.readyState == 4) 
	    {
	       
       		updateTopapgeResultpage(self.xmlHttpReq.responseText,span);
       	
			
        }
	}
    self.xmlHttpReq.send(getquerystring(formName));
}

function updateTopapgeResultpage(str,span)
{ 
//alert(str);
if(trim(str)=='guest')
{
var newsForm=document.getElementById('eNewsletter');
if(newsForm!=null){
newsForm.action=document.getElementById('eNewsletterSignup').value;
//alert(newsForm.action);
newsForm.submit(); }
}
else
{
var errorEnewslettEmail=document.getElementById('errorEnewslettEmail');
if(errorEnewslettEmail!=null){
errorEnewslettEmail.innerHTML=trim(str);
errorEnewslettEmail.style.display="block";}
}
	
}

function getquerystring(formName) 
{
    var qstr = "";
   
	for(j=0;j<formName.elements.length;++j) 
	{
		if(formName.elements[j].type=='radio' )
	 	{
			if(formName.elements[j].checked)
			qstr += formName.elements[j].name + "=" + escape(trim(formName.elements[j].value)) + "&";
		}
		else if(formName.elements[j].type=='checkbox' )
		{
			if(formName.elements[j].checked)
			qstr += formName.elements[j].name + "=" + escape(trim(formName.elements[j].value)) + "&";
		}
		else if(formName.elements[j].name != "")
		{
		
			if(formName.elements[j].value!=null && trim(formName.elements[j].value).length>0)
			{
				val = escape(trim(formName.elements[j].value));
				EscVal = specialCharEscape(val);
				qstr += formName.elements[j].name + "=" + EscVal + "&";
			}
		}
    }
          
        return qstr;
}

function trim(str){return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');}
	
function specialCharEscape(htmlval)
{
	htmlval = htmlval.replaceAll("*", "%2A");
	htmlval = htmlval.replaceAll("+", "%2B");
	htmlval = htmlval.replaceAll("-", "%2D");
	htmlval = htmlval.replaceAll(".", "%2E");
	htmlval = htmlval.replaceAll("/", "%2F");
	htmlval = htmlval.replaceAll("@", "%40");
	/*
	htmlval = htmlval.replaceAll("_", "%2B");
	*/	
	return htmlval;
}

String.prototype.replaceAll = function(s1, s2) 
{ 
	return this.split(s1).join(s2); 
}

	
