var FreshCo_isNav4 = (document.layers) ? 1 : 0;
var FreshCo_isNav6 = (document.getElementById) ? 1 : 0;
var FreshCo_isIE4Up = (document.all) ? 1 : 0;
var FreshCo_isMac = (navigator.appVersion.indexOf('Mac')!= -1)? 1:0 
var FreshCoFlyOutTimerObj = new Array();
var FreshCoFlyOutZIndex = new Array();
var FreshCoOriginalGlobalNav = "";
var FreshCoZIndex = 4100;


function FreshCoAddOnloadEvent(fnc){
  if ( typeof window.addEventListener != "undefined" )
    window.addEventListener( "load", fnc, false );
  else if ( typeof window.attachEvent != "undefined" ) {
    window.attachEvent( "onload", fnc );
  }
  else {
    if ( window.onload != null ) {
      var oldOnload = window.onload;
      window.onload = function ( e ) {
        oldOnload( e );
        window[fnc]();
      };
    }
    else
      window.onload = fnc;
  }
}

function FreshCoChangeClass(id, newclass) {
	
	var identity=document.getElementById(id);
	if(document.All)identity.setAttribute("className", newclass);
	else identity.className=newclass;
}

function FreshCoGetClassName(id){
	var identity=document.getElementById(id);
	if(identity!=undefined){
		if(document.All)return identity.getAttribute("className");
		else return identity.className;
	}
}

function FreshCofindPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function FreshCofindPosY(obj)
{
	var curtop = 0;
	var printstring = '';
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			printstring += ' element ' + obj.tagName + ' has ' + obj.offsetTop;
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function FreshCoGetXY(obj)
{
  var curleft = 0;
  var curtop = obj.offsetHeight + 5;
  var border;
  if (obj.offsetParent)
  {
    do
    {
      // XXX: If the element is position: relative we have to add borderWidth
      if (FreshCogetStyle(obj, 'position') == 'relative')
      {
        if (border = _pub.FreshCogetStyle(obj, 'border-top-width')) curtop += parseInt(border);
        if (border = _pub.FreshCogetStyle(obj, 'border-left-width')) curleft += parseInt(border);
      }
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    }
    while (obj = obj.offsetParent)
  }
  else if (obj.x)
  {
    curleft += obj.x;
    curtop += obj.y;
  }
  return {'x': curleft, 'y': curtop};
}

function FreshCogetStyle(obj, styleProp)
{
  if (obj.currentStyle)
    return obj.currentStyle[styleProp];
  else if (window.getComputedStyle)
    return document.defaultView.getComputedStyle(obj,null).getPropertyValue(styleProp);
}


	function FreshCoshowMenu(ID,img,xOff,yOff){
		FreshCoSustainMenu(ID);
		var obj = document.getElementById(img);
		
		var pos = FreshCoGetXY(obj)
		var ieversion = 20;
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
 			ieversion=new Number(RegExp.$1) 
		}
		var newX = pos.x - xOff;
		if (ieversion <7){
		//	var logo = document.getElementById("logo");
		//	var logopos = FreshCoGetXY(logo)
		//	newX = logopos.x + xOff
			//if(img.indexOf("flyer") > -1)xOff+=300;
		///	//else if(img.indexOf("good") > -1)xOff+=200;
		}
		
		//newX = getAbsPos( document.getElementById(img) ,"Left");
		var newY =  FreshCofindPosY( obj)+yOff;//9;
		var navItem = document.getElementById(ID).style;
	
		navItem.xpos = parseInt(newX);//parseInt(navItem.left);	
		navItem.ypos = parseInt(newY);//parseInt(navItem.top);
		
		navItem.left = navItem.xpos+"px";	
		navItem.top =  navItem.ypos+"px";
		navItem.visibility="visible";
		if(FreshCoFlyOutZIndex[ID]==null)FreshCoFlyOutZIndex[ID] = navItem.zIndex;
		navItem.zIndex = FreshCoZIndex++;
		FreshCoShow_hideCurrentFade(ID,true);
	
		if(obj.src!=undefined)
	    	obj.src = obj.src.replace("_off","_on");
		var parentClass =FreshCoGetClassName(img);
		if(parentClass.substr(parentClass.length-2,2)!="On")FreshCoChangeClass(img, parentClass+"On")
	
	}
	
	function FreshCoSustainMenu(ID){
		clearTimeout(FreshCoFlyOutTimerObj[ID]);
		FreshCoFlyOutTimerObj[ID] = null;
	}
	
	function FreshCoHideMenu(ID,other){
		FreshCoFlyOutTimerObj[ID] = window.setTimeout("FreshCohideIt('"+ID+"','"+other+"')",400);
	}
	
	function FreshCohideIt(ID,other){
		navItem = document.getElementById(ID).style;
		navItem.visibility="hidden";
		if(FreshCoFlyOutZIndex[ID]!=null)navItem.zIndex =FreshCoFlyOutZIndex[ID];
		if(ID !="product_sub_nav")navItem.display="none";
		var obj = document.getElementById(other);
		//alert(other+" "+FreshCoOriginalGlobalNav+" "+obj)
		if(obj!=undefined&&other.toLowerCase() != FreshCoOriginalGlobalNav.toLowerCase()){
			var parentClass =FreshCoGetClassName(other);
			if(parentClass!=undefined){
		   	 if(parentClass.substr(parentClass.length-2,2)=="On")FreshCoChangeClass(other, parentClass.substr(0,parentClass.length-2))
			}
		}
	}
	

	function FreshCoArcDimension(obj){
		if ( obj.currentStyle ) {
			return {height:obj.currentStyle.height,width:obj.currentStyle.width,top:obj.currentStyle.top,left:obj.currentStyle.left};
		} else if ( document.defaultView.getComputedStyle ){
				return {height:document.defaultView.getComputedStyle(obj,'').height,width:document.defaultView.getComputedStyle(obj,'').width,top:document.defaultView.getComputedStyle(obj,'').top,left:document.defaultView.getComputedStyle(obj,'').left};
		} else {
			return {height:obj.style.height,width:obj.style.width,left:obj.style.left,top:obj.style.top};
		}	
	}


function FreshCoShow_hideCurrent(id,show){
	if(show)document.getElementById(id).style.display = "block";
	 else document.getElementById(id).style.display = "none";
}

function FreshCoShow_hideCurrentFade(id,show){
	if(show)$("#" + id).fadeIn(300);
	else $("#" + id).fadeOut(100);
}

function FreshCoPopUp(URL,w,h) {
	FreshCoPopUpScroll(URL,w,h,"1")
}

function FreshCoPopUpNoScroll(URL,w,h){
	FreshCoPopUpScroll(URL,w,h,"0")
}
function FreshCoPopUpScroll(URL,w,h,scroller){
	var newwin = window.open(URL, 'freshpop', 'toolbar=0,scrollbars='+scroller+',location=0,statusbar=0,menubar=1,resizable=1,width='+w+',height='+h+',left = 420,top = 150');
	newwin.focus();
}
function FreshCoSetObjectContent(str,obj){
	obj.innerHTML = str;
}
function FreshCoWinWidth(){
	return (FreshCo_isIE4Up)?(document.body.scrollWidth)+"px":(window.innerWidth-17)+"px";
}
function FreshCoWinHeight(){
	return (FreshCo_isIE4Up)?(document.body.scrollHeight)+"px":(window.innerHeight)+"px";
}

function FreshCoScreenHeightWidth(){
	 var viewportwidth;
	 var viewportheight;
	 if (typeof window.innerWidth != 'undefined')
	 {
		  viewportwidth = window.innerWidth,
		  viewportheight = window.innerHeight
	 }
	else if (typeof document.documentElement != 'undefined'&& typeof document.documentElement.clientWidth !='undefined' && document.documentElement.clientWidth != 0)
	 {
		   viewportwidth = document.documentElement.clientWidth,
		   viewportheight = document.documentElement.clientHeight
	 }
	 else
	 {
		   viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		   viewportheight = document.getElementsByTagName('body')[0].clientHeight
	 }
		return {height:viewportheight, width:viewportwidth}
}

function FreshCoShowOverlay(ID){
	var obj = document.getElementById(ID);
	var overlay = document.getElementById(ID);
	//if(obj!=undefined){
		overlay.innerHTML = obj.innerHTML+"";
		freshCoCenterDiv(overlay)
		if(FreshCo_isIE4Up)FreshCoShow_hideCurrent(ID,true);
		else FreshCoShow_hideCurrentFade(ID,true);
	//}
	
}

function FreshCoShowOverlay1(ID){
	var obj = document.getElementById(ID);
	var overlay = document.getElementById('freshcoMainOverlay');
	//if(obj!=undefined){
		overlay.innerHTML = obj.innerHTML+"";
		freshCoCenterDiv(overlay)
		if(FreshCo_isIE4Up)FreshCoShow_hideCurrent('freshcoMainOverlay',true);
		else FreshCoShow_hideCurrentFade('freshcoMainOverlay',true);
	//}
	
}

function FreshCoshowOverlayConfirm(str){
		var olay = document.getElementById('freshcoconfirmoverlaycontent');
		olay.innerHTML = str;
		var overlay = document.getElementById('freshcoMainOverlayConfirm');
		freshCoCenterDiv(overlay)
		if(FreshCo_isIE4Up)FreshCoShow_hideCurrent('freshcoMainOverlayConfirm',true);
		else FreshCoShow_hideCurrentFade('freshcoMainOverlayConfirm',true);
}


function freshCoScrollH(){
	
var ScrollTop = document.body.scrollTop;

if (ScrollTop == 0)
{
    if (window.pageYOffset)

        ScrollTop = window.pageYOffset;

    else

        ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
}	
return ScrollTop
}

function freshCoCenterDiv(overlay){
	    overlay.style.visibility = "hidden";
		overlay.style.display = "block";
		var posX = (parseInt(FreshCoScreenHeightWidth().width)/2) - (parseInt(overlay.offsetWidth)/2);
		var posY = ((parseInt(FreshCoScreenHeightWidth().height))/2) - (parseInt(overlay.offsetHeight)/2)+(freshCoScrollH());

		overlay.style.left = posX+"px";
		overlay.style.top = posY+"px";
		overlay.style.display = "none";
		overlay.style.visibility = "visible";
}

function FreshCoisValidEmail(strEmail){
  var validRegExp = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
     // search email text for regular exp matches
    if (strEmail.search(validRegExp) == -1) 
   {
      return false;
    } 
    return true; 
}

   function FreshCoisValidp_code(p)
{
     //create regular expression for testing
     var reg_exp_pcode = new RegExp(/(^s*([a-z](\s)?\d(\s)?){3}$)s*/i);

     if(!reg_exp_pcode.test(p))
     {
          return(false);
     }
     return(true);
}

function FreshCoEnewsSignUpThankYou(){
	var formdiv = document.getElementById("freshcosignupformdiv");
	formdiv.style.display = "none";
	FreshCoShow_hideCurrentFade("freshcothankyouforsigningup",true)
	
}

function FreshCoEnewsSignUpError(){
	FreshCoshowOverlayConfirm("An error occured during the signup process. Please try again at a later time.")
}

function FreshCoEnewsSignUpPostalError(){
	FreshCoshowOverlayConfirm("The postal code you have entered could not be found in the Canada Post database. Please confirm your postal code and try again.")
}

function FreshCoSubmitEflyer(){
	var err = false;
	var errStr = "<div style=\"margin-bottom:15px\"><b>Please complete the following fields correctly before clicking submit</b></div><ul  class=\"error\">";
	var email = document.getElementById("emaileflyer").value
	var confirmemail = document.getElementById("confirmEmaileflyer").value
	var firstname = document.getElementById("firsteflyer").value
	var lastname = document.getElementById("lasteflyer").value
	var postal1 = document.getElementById("postaleflyer1").value
	var postal2 = document.getElementById("postaleflyer2").value
	var flyer = (document.getElementById("optIneflyer").checked)? "yes":""
	var sobey = (document.getElementById("optInemaileflyer").checked)? "yes":""
	//alert(email+" "+document.getElementById("confirmEmaileflyer").value+" ")
	if(!FreshCoisValidEmail(email)){
		errStr += "<li>A valid email address</li>";
		err=true;	
	}
	
	if(confirmemail!=email){
		errStr += "<li>Confirm your email address</li>";
		err=true;	
	}
	
	if(firstname==""){
		errStr += "<li>Your first name</li>";
		err=true;	
	}
	
	if(lastname==""){
		errStr += "<li>Your last name</li>";
		err=true;	
	}
	if(!FreshCoisValidp_code(postal1+postal2)){
		errStr += "<li>A valid postal code</li>";
		err=true;	
	}
	
	if(err){
		FreshCoshowOverlayConfirm(errStr+"</ul>")
	//alert(errStr)	
	}else{
		var ss = document.getElementById("freshcoscriptdiv");
		var scriptObj = document.createElement("script");
		scriptObj.setAttribute("type", "text/javascript");
		scriptObj.setAttribute("charset", "utf-8");
		scriptObj.setAttribute("src", 'http://www.freshco.com/cmspages/fc/eflyersubscribe.aspx?email='+email+'&email_confirm='+confirmemail+'&fname='+firstname+'&lname='+lastname+'&zip1='+postal1+'&zip2='+postal2+'&eflyer='+flyer+'&inspired=&otherPromotions='+sobey);
		scriptObj.setAttribute("id", "freshcoscriptdivSCRIPT");
		ss.appendChild(scriptObj);
		//http://www.info-sobeys.com/subscribe_update.asp?email=add%40asdsd.com&email_confirm=add%40asdsd.com&fname=asfassdfasdf&lname=sffsdfsf&zip1=l6c&zip2=2h3&eflyer=yes&inspired=yes&otherPromotions=yes&id=
		//ss.innerHTML = '<script language="JavaScript" src="/cmspages/fc/eflyersubscribe.aspx?email='+email+'&email_confirm='+confirmemail+'&fname='+firstname+'&lname='+lastname+'&zip1='+postal1+'&zip2='+postal2+'&eflyer='+flyer+'&inspired=&otherPromotions='+sobey+'"></script>'

	}
}

$(document).ready(function(){ 
	$("#plcRoot_Layout_zoneContent_pageplaceholder_partPlaceholder_Layout_zoneLeft2_form_ctl00_Bizform1_ctl00_btnOK").hover(
		function(){ this.src="/app_themes/freshco/images/btn_sendON.gif"; },
		function(){ this.src="/app_themes/freshco/images/btn_send.gif"; }
	);

	$("#btn-eflyerSubmit").hover(
		function(){ this.src="/app_themes/freshco/images/btn_submitON.gif"; console.log("over!");},
		function(){ this.src="/app_themes/freshco/images/btn_submit.gif"; }
	);

}); /* document ready */ 
