var markeractive=false;
var flagsactive=false;
var flagsdefined=false;
var imagespreloaded=true;
var flagsarray = new Array();
var myflag = new Array();
var usersession = new Object();
usersession.sessionid="";
var isanswersubmitted= 0;
var flagcount =0;
var tacloaded = 0;
var galimages = new Array();
var imgPreloadNames = new Array();
var imgPreloadIterator = 0;
var flagsloaded = false;
var loadPrizePause1;
var loadPrizePause2;
var loadPrizePause3;
var prizePanelOpen = false;
var currentflag;
$(document).ready(function(){
	//AJAX Animation
	$("a").hover(
		function(){
			$(this).addClass("cursorstate");
		},
		function(){
			$(this).removeClass("cursorstate");
		}
	);	    		
	$("#sharethis").click(function(){
		$("#sharelinks").toggle();
	});	
	$("#sharelinksbox").mouseout(function(){
		$("#sharelinks").css("display", "none");
	});	
	$("img.rollover").hover(
		function(){ 
			this.src = this.src.replace("_off","_on");			    
		},
		function(){ 
			this.src = this.src.replace("_on","_off");			    
		}
	);	
	if (siteLevel == "sweeps") {
//		$("#ajaxloading").css('visibility','visible').fadeIn(0);
		//Create Flash Objects
		//Flags
		if (swfobject.hasFlashPlayerVersion("9")) {
			for(var ffile=1;ffile<=5;ffile++){
				  var att = { "class":"ff", data:"flag" + ffile + ".swf", width:"60", height:"160" };
				  var par = {  menu:"false", wmode:"transparent" };
				  var id = "flag" + ffile;			  
				  myflag[ffile] = swfobject.createSWF(att, par, id);
			}
		}
		//Pin
		var att = { data:"pin.swf", width:"60", height:"160" };
		var par = { menu:"false", wmode:"transparent" };
		var id = "pin";
		mypin = swfobject.createSWF(att, par, id);
		//banner
		start_slideshow(1, 3, bannertimeout);
		//open main panel
		loadinfo("enter");

}
	if (siteLevel == "root") {
		ajaxHourglass("on");
		//used to set scrollbar in accordion
		$('.scroll-pane').jScrollPane({scrollbarWidth:3, scrollbarMargin:2, dragMinHeight:42, dragMaxHeight:42 });	
		//used for accordion
		$("#accordion").accordion({	header:'.fx-accordion-tab'});
		// Toggle accordian up/down button image
		$('#accordion').find("h3").click(
			function(){
				var kclass = $(this).hasClass("bottom") ?"bottom":"top";
				if(kclass=="top")
				{			    
					$('#accordion h3:eq(0)').removeClass("ui-helper-reset");
					$('#accordion h3:eq(1)').removeClass("ui-helper-reset");
					$('#accordion h3:eq(0)').removeClass("ui-state-default");
					$('#accordion h3:eq(1)').removeClass("ui-state-default");				
					$('#accordion h3:eq(0)').removeClass("ui-state-top-inactive");
					$('#accordion h3:eq(0)').addClass("ui-state-top-active");
					$('#accordion h3:eq(1)').removeClass("ui-state-bottom-active");
					$('#accordion h3:eq(1)').addClass("ui-state-bottom-inactive");
				}
				else{
					if(kclass=="bottom")
					{
						$('#accordion h3:eq(0)').removeClass("ui-helper-reset");
						$('#accordion h3:eq(1)').removeClass("ui-helper-reset");
						$('#accordion h3:eq(0)').removeClass("ui-state-default");
						$('#accordion h3:eq(1)').removeClass("ui-state-default");	
						$('#accordion h3:eq(0)').removeClass("ui-state-top-active");				
						$('#accordion h3:eq(0)').addClass("ui-state-top-inactive");
						$('#accordion h3:eq(1)').removeClass("ui-state-bottom-inactive");
						$('#accordion h3:eq(1)').addClass("ui-state-bottom-active");
					}				
				}
			}
		);			
		$("#sched").click(function(){
			$("#outlook").toggle();
		});
		$("#close-out").click(function(){
			$("#outlook").toggle();
		});
	}	
});

function start_slideshow(start_frame, end_frame, delay) {
	setTimeout(switch_slides(start_frame,start_frame,end_frame, delay), delay);
}

function switch_slides(frame, start_frame, end_frame, delay) {
	return (function() {
		$('#banner' + frame).fadeOut(1000);
		if (frame == end_frame) { frame = start_frame;} else { frame++;}
		setTimeout("$('#banner" + frame + "').fadeIn(2000);", 0);			
		setTimeout(switch_slides(frame, start_frame, end_frame, delay), delay );
	})
}

//share this links
function showfwlist(){
  $("#sharelinks").css("display","block");
}

function hidefwlist(){
  $("#sharelinks").css("display","none");
}
//tool tips for flags
function tooltipout(tooltipid){
  $("." + tooltipid).css("display","none");
}
	
function tooltipover(tooltipid,name){
   if(($("#emailfbox").css("display") == "none" || $("#emailfbox").css("visibility") == "hidden") && ($("#fpassbox").css("display") == "none" || $("#fpassbox").css("visibility") == "hidden"))
   {
	if(name)
	{	
		var mtop = parseInt(parseInt($(".pin-1").css("top").replace("px","")) + 40) + "px";
		var mleft = parseInt(parseInt($(".pin-1").css("left").replace("px","")) - 40) + "px";
		$("." + tooltipid).css("top",mtop);	
		$("." + tooltipid).css("left",mleft);			
	}
	$("." + tooltipid).css("display","block");
	$("#flag1active").css("cursor","pointer");
	$("#flag2active").css("cursor","pointer");
   }
   else
	{
      $("#flag1active").css("cursor","none");	  
	  $("#flag2active").css("cursor","none");
	}   
}
 //Preload Images
function preloadimages(){   	
    var j =0;
	//ajaxHourglass("off");
		//$("#ajaxloading").css('visibility','visible').fadeIn(0);
		$.getJSON(pathtojson, function(data){		
        $.each(data.prizes, function(_ind, _el){	        
            $.each(_el.images,function(i,item) {
                //galimages[j] = new Image();
				//galimages[j] = document.createElement("img");
                //galimages[j].src = item.image;
				imgPreloadNames.push(item.image);
				//pausecomp(250);
				//$('.profile').append(galimages[j])
                //j++;
            });
        });		
		setTimeout("preloadimagesasynch()", 500);
		//alert(imgAry.toString());
		//loadhtml("landingpage.html","enter",".all-sweepstakes");	
    });
}
function preloadimagesasynch() {	
	var imgTemp = new Image();
	imagespreloaded = false;
	imgTemp.onload = function() {
		galimages[imgPreloadIterator] = this;
		$('.profile').append(galimages[imgPreloadIterator])
		imgPreloadIterator++;
		if (imgPreloadIterator < imgPreloadNames.length) {
			setTimeout("preloadimagesasynch()", 50);
		} else {
			prizePanelOpen = false;
			setTimeout("loadprizeoverflow(); imagespreloaded = true; ajaxHourglass('on');", 50);
		}		
	};	
	imgTemp.src = imgPreloadNames[imgPreloadIterator];
	//galimages[imgPreloadIterator] = new Image();
	//galimages[imgPreloadIterator].src = imgPreloadNames[imgPreloadIterator];
	//$('.profile').append(galimages[imgPreloadIterator])
	//imgPreloadIterator++;
}

function loadinfo(type){
    switch(type)
    {		
		case "tac":
			$("#closeprize").click();
			/*
		    hidecontent('closeprize');				
			$("#prizeboxcont").css("visibility","hidden");
			$(".map-txt").css("display","block");				
			$('#rolle').css("visibility","visible");	
			$('.map-txt').css("visibility","visible");				
			$("#flashqmarkercont").css("z-index","-100");
			*/
			prizePanelOpen = false;
            loadhtml("terms.html","scroller","#tosbox");
            break;
        case "stf":
			$("#closeprize").click();
			$("#flag1active").css("cursor","none");	  
			$("#flag2active").css("cursor","none");
			/*
		    hidecontent('closeprize');				
			$("#prizeboxcont").css("visibility","hidden");
			$(".map-txt").css("display","block");				
			$('#rolle').css("visibility","visible");	
			$('.map-txt').css("visibility","visible");				
			$("#flashqmarkercont").css("z-index","-100");
			*/
			prizePanelOpen = false;
            loadhtml("emailfriend.html","sendtofriend","#emailfbox");
            break;
        case "fp":
            loadhtml("forgotpassword.html","forgotpassword","#fpassbox");					
			$("#flag1active").css("cursor","none");	  
			$("#flag2active").css("cursor","none");
            break;	
        case "enter":
			loadhtml("landingpage.html","enter",".all-sweepstakes");
			/*if(!imagespreloaded)
		    {
		        preloadimages();
		    }*/
            break;
    }
}

function hidecontent(divid){
	if(divid == "fpsuccess")
	{
		$("#fpassbox").css("visibility","hidden");
		return;
	}
	if(divid == "stfsuccess")
	{
		$("#emailfbox").css("visibility","hidden");
		return;
	}	
	
	if(divid=="register")
	{
	  
	  $("#gall-next").css("display","none");	  
	  $("#gall-next").css("visibility","hidden");
	  $("#gall-back").css("display","none");
	  $("#gall-back").css("visibility","hidden");
	}
    $("#landingpage").css("visibility","hidden");
    $("#registrationpage").css("visibility","hidden");
    $("#welcome").css("visibility","hidden");
    $("#sweepsclosed").css("visibility","hidden");
    $("#winnerannounced").css("visibility","hidden");
    $("#registerconfirm").css("visibility","hidden");
    $("#welcomeback").css("visibility","hidden");
    $("#alreadyanswered").css("visibility","hidden");
    $("#loginpage").css("visibility","hidden");
    $('.map-txt').css("visibility","hidden");	
	$('.legal .map-txt').css("visibility","hidden");		
	$('#trivia-q').css("visibility","hidden");	        
    $('.logo-bl').css("visibility","hidden");	
	$("#q-submit").css("visibility","hidden");	
	$('#tour-h').css("visibility","hidden");		
	$('#emailfbox').css("visibility","hidden");	
	$('#emailfboxsuccess').css("visibility","hidden");	
	$('#errorbox').css("visibility","hidden");	
	$('#fpassbox').css("visibility","hidden");	
	$('#tosbox').css("visibility","hidden");	
	$('#fpassboxsuccess').css("visibility","hidden");	
	$('#q-stripe').css("visibility","hidden");	
	$('#q-stripe').css("display","none");
	$(".sweepstakes").removeClass("quiz");	
	$("#clickhere").css("visibility","hidden");	
	$('#reg-b').css("visibility","hidden");	
    $('#rolle').css("visibility","hidden");	
	if(flagsactive) 
	{
	    if(divid == "undefined" || (divid !="closeprize" && divid !="prize"))
	    {			
		    animateflags("up",false);	
		    $('#prizeboxcont').css("visibility","hidden");				    
		}

	}		       
	if(markeractive)
	{
		animatemarker("up");		
	}	
}

function loadhtmlcallback(page,type,divid,flagnum,top,left,errormessage,subdivid){	
    switch(type)
    {
        case "enter":						   										
			if(sweepstatus==1)
			{
				if($.cookie(cookiename)=="true" && $.cookie("email")!=null && $.cookie("password")!=null){
					setTimeout("login()", 1000);
				}
				else
				{										
                    loadhtml("welcome.html","form","#content","",0,0,"","#welcome");					
                    togglelogin("login");
				}
			}
			else if(sweepstatus==2)
			{			    
				loadhtml("sweepsclosed.html","","#content","",0,0,"","#sweepsclosed");									
				hidecontent();
			}
			else if(sweepstatus==3)
			{
                loadhtml("winnerannounced.html","","#content","",0,0,"","#winnerannounced");
				hidecontent();
			}
			if($("#whitebox").css("left")=="-540px")
            {
                showit(".map-txt",false);				
		        $("#whitebox").animate({"left":"34px"}, animatespeed);
		    }			
		    setTimeout("loadPrizeObjects()", 2000);
		    /*if($("#prizeoverflow").html()=="")
		    {			
				if(!imagespreloaded)
				{
					preloadimages();
				}
			    loadprizeoverflow();	
			}*/
			break;


		case "registerconfirm":
            hidecontent();
            $("#registerconfirm").css("visibility","visible");
            break;
		case "welcomeback":			
			hidecontent();
			$("#content").css("visibility","visible");
			$("#welcomeback").css("visibility","visible");
			break;
		case "alreadyanswered":
			hidecontent();
			$("#alreadyanswered").css("visibility","visible");
			break;
		case "showlogout":
			showit("#prizeboxcont",false);
			showit("#q-stripe",false)						
			showit("#tour-h",false);
			hidecontent();					
			$(subdivid).css("visibility","visible");	
			label2value();
			break;
		case "showlogin":
			showit("#login",false);
			showit("#tour-h",false);
			showit("#prizeboxcont",false);			
			hidecontent();					
			$(subdivid).css("visibility","visible");
			$("#loginerrorspan").css("display","none");
			$("#loginerrorspan").html("");
			//revivealert("$.cookie(cookiename): " + $.cookie(cookiename));
			//revivealert("$.cookie(\"email\"): " + $.cookie("email"));
			label2value();
			break;
		case "showregister":			
            hidecontent("register");		
            if($("#whitebox").css("left")=="-540px")
            {                		                
		        $("#whitebox").animate({"left":"34px"}, animatespeed);
		    }						
			$("#login").css("visibility","visible");
			$("#login").css("display","block");			
			$(subdivid).css("visibility","visible");			
			label2value();		
			jQuery(document.body).maxLengthFormControls();
			break;
		case "form":						
			hidecontent();			
			$(subdivid).css("visibility","visible");		
			label2value();			
			break;
		case "tryquestion":
		    hidecontent();			
		    $(".map-txt").css("visibility","visible");		 
		    $('.logo-bl').css("visibility","visible");	   
		    $('#clickhere').css("visibility","visible");	
			$(".sweepstakes").addClass("quiz");		
			if(isanswersubmitted == 0)
			{
				$("#questionchoices").css("display","block");
				$("#questiontitle").html(usersession.questiontitle);
				$("#questionbody").html(usersession.questionbody);
				$("#q-image").css("background-image","url(" + usersession.questionimage + ")");
				$("#lblanswerchoice1").html(usersession.answerchoice1);
				$("#lblanswerchoice2").html(usersession.answerchoice2);
				$("#lblanswerchoice3").html(usersession.answerchoice3);
				//$("#lblanswerchoice4").html(usersession.answerchoice4);				
				$("#q-submit").css("visibility","visible");
				$('#close-q').unbind('click');
				$("#close-q").click(function(){
				    $(".map-txt").css("visibility","visible");
				    animatemarker("down");	
					showit("#q-stripe",false,top,left);
				});						
				$("#q-submit").css("width","73px");
				$("#q-submit").css("height","25px");				
				$("#q-submit").css("margin","0 0 0 295px");
			}
			else
			{
			  $("#q-learnlink").css("display","block");
			  $("#q-learnlink").css("visibility","visible");			  
			}
			$("#q-learnlink img").css("width","299px");
			$("#q-learnlink img").css("height","17px");			  
			break;
		case "correctanswer":					   
			break;
		case "incorrectanswer":
			break;
		case "sendtofriend":
		    $("#message").text(defaultsendtofriendmessage);	
			$("#emailfsuccessbox").css("visibility","hidden");
			label2value();
			jQuery(document.body).maxLengthFormControls();
			break;
		case "forgotpassword":
			$("#fpasssuccessbox").css("visibility","hidden");
			label2value();			
			break;
		case "prize":	
			hidecontent("prize");
		    $('.logo-bl').css("visibility","visible");	  			 		
			opengallery(flagnum);
            $(".sweepstakes").addClass("quiz");
			$(".logo-bl").css("display","block");	
			$(".logo-bl").css("visibility","visible");	
			$('#closeprize').unbind('click');
			$("#closeprize").click(function(){	
				prizePanelOpen = false;
			    hidecontent('closeprize');				
			    $(".map-txt").css("display","block");				
                $('#rolle').css("visibility","visible");	
                $('.map-txt').css("visibility","visible");				
		        if(usersession  && usersession.sessionid)
			    {			
					if(typeof usersession!="undefined"){
						if(usersession.questioncompleted=="1"){                    
							$('#trivia-q').css("visibility","hidden");
						}
					}
			    }
			    else
			    {
			       $('#reg-b').css("visibility","visible");
			    }
			        
	            $('.logo-bl').css("visibility","visible");											    						    
				$("#rolle").css("display","block");	
				$("#rolle").css("visibility","visible");	
				var mtop= $(".flag" + flagnum + "-1").css("top").replace("px","");
				mtop = parseInt(parseInt(mtop) - 245);
				showit("#prizeboxcont",false,mtop +"px",$(".flag" + flagnum + "-1").css("left"));								
			});
			$('#prizeboxcont').css("visibility","visible");														
			showit(".map-txt",false);
			showit("#tour-h",true);	
			
			if(usersession  && usersession.sessionid)
			{			
				if(typeof usersession!="undefined"){
					if(usersession.questioncompleted=="1"){                    
						$('#trivia-q').css("visibility","hidden");
					}
				}
			}
			else
			{
			   $('#reg-b').css("visibility","visible");
			}			   
			break;
		case "error":					
			$(".errmsg").html(errormessage);						
			break;
		case "scroller":
			if(tacloaded==0)
			{
				$('#scroll-txtcont').jScrollPane({scrollbarWidth:14, scrollbarMargin:0, showArrows:true, dragMinHeight:42, dragMaxHeight:42 });																	
				tacloaded++;
			}	
			break;
	}
	//Load Common JS Routines for newley loaded DOM elements
	// Rollover Images
	$(function(){
		$("img.rollover").hover(
			function () { this.src = this.src.replace("_off","_on");
			},
				function () { this.src = this.src.replace("_on","_off");
			}
		);
	});
	//Anchor Hover Cursor
	$("a").hover(
			function(){
				$(this).addClass("cursorstate");
			},
			function(){
				$(this).removeClass("cursorstate");
			}
	);
	//style checkboxes and radio buttons
	$('input:checkbox:not([safari])').checkbox();
	$('input[safari]:checkbox').checkbox({cls:'jquery-safari-checkbox'});
	$('input:radio').checkbox();

    displayForm = function (elementId)
    {
        var content = [];
        $('#' + elementId + ' input').each(function(){
            var el = $(this);
            if((el.attr('type').toLowerCase() == 'radio'))
            {
                if (this.checked)
                    content.push([
                        '"', el.attr('name'), '": ',
                        'value="', (this.value), '"',
                        (this.disabled ? ', disabled':'')
                    ].join(''));
            }
            else
            {
                content.push([
                    '"', el.attr('name'), '": ',
                    (this.checked ? 'checked':'not checked'), 
                    (this.disabled ? ', disabled':'')
                ].join(''));
            }
        });
    }
    //run our code to show the div
	showit(divid,true,top,left);		
}

function loadhtml(page,type,divid,flagnum,top,left,errormessage,subdivid){
	if(($(divid).html() == "") || (subdivid != undefined && ($(divid).html() != "" || $(divid).html() == null) && ($(subdivid).html() == "" || $(subdivid).html()==null)))
	{				
		$(($(divid).html() =="")?divid:subdivid).load(page,
			function(){	
				if(($(divid).html() =="")?divid:subdivid)
				{				    
					$(($(divid).html() =="")?divid:subdivid).css("visibility","visible");	
				}
				loadhtmlcallback(page,type,divid,flagnum,top,left,errormessage,subdivid);
			}
		);
	}
	else
	{				
		loadhtmlcallback(page,type,divid,flagnum,top,left,errormessage,subdivid);		
	}
}

function fixform(postdata,fieldname)
{
	var indexofphone = postdata.indexOf("&" + fieldname + "=");										
	var restofstring = postdata.substring(indexofphone + fieldname.length + 2);					
	var oldphonenumber = restofstring.substr(0,restofstring.indexOf("&"));					
	newphonenumber = oldphonenumber.replace(/\D/g,"");								
	postdata = postdata.replace("&" + fieldname + "=" + oldphonenumber + "&", "&" + fieldname + "=" + newphonenumber + "&");
	return postdata;
}
function htmlpost(url,action,data,rememberme,answer,formid){
	//alert("htmlpost. url: " + url + ", action: " + action + ", data: " + data + ", rememberme: " + rememberme + ", answer: " + answer + ", formid: " + formid);	
    var postdata = ""	
    if(data == ""){
        postdata = $(formid).serialize();
		//postdata = removeField(postdata, "password-decoy");
		switch(action)
		{
			case "login":																
			case "register":
					deletecookies(cookiename);
				    if(postdata.indexOf("&tac=1") == -1)
					{
					  loadhtml("error.html","error","#errorbox",1,1,1,"You must agree to the terms and conditions before registering.");
					  return;
					}
					postdata = postdata.replace("&tac=1","");					
			        if(postdata.indexOf("shipinfo") == -1)
			        {
			          postdata += "&shipinfo=0";
			        }
			        if(postdata.indexOf("sendreminders") == -1)
			        {
			          postdata += "&sendreminders=0";
			        }															
					var errorMsg = validateRegistration(postdata);
					if (errorMsg!="") {
						loadhtml("error.html","error","#errorbox",1,1,1,errorMsg);
						return; //break out of this function to prevent AJAX submission
					}					
					postdata = fixform(postdata,"phone");					
					postdata = postdata.replace("Business+name+(optional)","n/a");
					break;
			case "stf":
					break;
			case "fp":
					break;		
		}		        
    } else {
        postdata = data;		
    }   
	if(action=="login")
	{
		$("#loginerrorspan").css("display","none");
		$("#loginerrorspan").html("");
	}	
	postdata+="&chksum=" + hex_md5(createmd5string(postdata,action));	
	//alert(postdata);	
    var password=$("input#welcome2").val();
    $.ajax(
        {
            type:"POST",
            url:url,
            dataType:"xml",
            data:postdata,
            timeout:timeout,
            success:function(xml){				  
				  //processresponse(xml,action,rememberme,password,answer);
				  loadhtml("error.html","error","#errorbox",1,1,1,communicationserrormsg);
            },
            error:function(xml, msg){
				//alert(msg + XMLtoString(xml));
				$("#errorbox").css("visibility","visible");
				loadhtml("error.html","error","#errorbox",1,1,1,communicationserrormsg);
            }					
        }
    );
}

function processresponse(xml,action,rememberme,password,answer){
	//revivealert("ReturnXML: " + XMLtoString(xml));
    $(xml).find(xmlrootnode).each(function(){
        var string = xml.xml;
        var status = $(this).find("status").attr("value");
		switch (action)
		{		
		case "login":
		case "register":
            if(status == "1"){
                processxml(xml,action,rememberme,password);	
            } else {
				$("#errorbox").css("visibility","visible");
				var errmsg = $(this).find("status").attr("value");
				var errorfield = "";
				if (errmsg == "already registered") {
					errmsg = "You have already registered for the sweepstakes.";
				}
				if (errmsg.indexOf("checksum") > -1) {
					errmsg = "There seems to be a problem with your registration information. Please ensure that you have not entered any special characters such as \"% & }\", etc.";
				}
				if(typeof $(this).find("errorfield").attr("value")!="undefined" && $(this).find("errorfield").attr("value")!=""){
				    errmsg += "<br />" + $(this).find("errorfield").attr("value");
				}
				if(action=="login")
				{
					$("#loginerrorspan").css("display","block");
					deletecookies();
					switch(errmsg)
					{
						case "not registered":
							errmsg = "Incorrect Email/Password Combination. Please try again.";							
							break;
					}
					$("#loginerrorspan").html(errmsg);					
				}
				else
				{
					loadhtml("error.html","error","#errorbox",1,1,1,errmsg);
				}
            }
			break;
		case "answer":
			//tracking code
			var axel = Math.random()+"";
			var a = axel * 10000000000000;
			var img = new Image();
			img.src = "http://ad.doubleclick.net/activity;src=1186546;type=2009s813;cat=answe463;ord="+ a + "?";
            if(status == "1"){
                if(answer==usersession.correctanswer){							
					$("#questionchoices").css("display","none");
                    $("#q-submit").css("visibility","hidden");																				
                    $("#q-image").css("background-image","url(" + usersession.correctresponseimage + ")");
                    $("#questiontitle").html(usersession.correctresponsetitle);
                    $("#questionbody").html(usersession.correctresponsebody);
					$("#q-learnlink").css("visibility","visible");					
                }else{                   
					$("#questionchoices").css("display","none");
                    $("#q-submit").css("visibility","hidden");
					$("#q-learnlink").css("visibility","visible");										
                    $("#q-image").css("background-image","url(" + usersession.incorrectresponseimage + ")");
                    $("#questiontitle").html(usersession.incorrectresponsetitle);
                    $("#questionbody").html(usersession.incorrectresponsebody);
                }			
            } else{
				$("#errorbox").css("visibility","visible");		
				var errorMsg = $(this).find("status").attr("value");
				if (errorMsg == "bad answer") {
					errorMsg = "Please select an answer.";
				}
				loadhtml("error.html","error","#errorbox",1,1,1,errorMsg);
            }
			break;
		case "logout":
			break;
            if(status == "1"){                
            } else{
                loadhtml("error.html","error","#errorbox",1,1,1,$(this).find("status").attr("value"));
            }
			break;
		case "stf":		
			hidecontent("stfsuccess");
			$("#emailfsuccessbox").css("visibility","visible");
			if(status == "1")
			{				
				loadhtml("emailfriend-c.html","","#emailfsuccessbox");
			}
			else
			{
				$("#errorbox").css("visibility","visible");				
				loadhtml("error.html","error","#errorbox",1,1,1,$(this).find("status").attr("value"));
			}			
			break;
		case  "fp":					
			hidecontent("fpsuccess");
			$("#fpasssuccessbox").css("visibility","visible");
			if(status == "1")
			{								
				loadhtml("forgotpassword-c.html","","#fpasssuccessbox");
			}
			else
			{
				$("#errorbox").css("visibility","visible");				
				loadhtml("error.html","error","#errorbox",1,1,1,$(this).find("status").attr("value"));
			}
			break;
		}		
    });	
}

function processxml(xml,action,rememberme,password){
    $(xml).find(xmlrootnode).each(function(){	
		//alert($(xml).xml);
		switch(action)
		{
			case "login":
			case "register":
	            //Create new usersession object to store our variables
	            usersession = new Object();	            
	            //Get the question location coordinates and set them to an array	            
	            usersession.sessionid = $(this).find("sessionid").attr("value");
	            usersession.session_expire = $(this).find("session_expire").attr("value");
	            usersession.firstname = $(this).find("firstname").attr("value");
	            usersession.lastname = $(this).find("lastname").attr("value");
	            usersession.email = $(this).find("email").attr("value");	            
				usersession.questionlocationleft = $(this).find("iconposx").attr("value");	            
				usersession.questionlocationtop = $(this).find("iconposy").attr("value");
	            usersession.questioncompleted = $(this).find("questioncompleted").attr("value");
	            usersession.questiontitle = $(this).find("questiontitle").attr("value");
	            usersession.questionbody = $(this).find("questionbody").attr("value");
	            usersession.answerchoice1 = $(this).find("answerchoice1").attr("value");
	            usersession.answerchoice2 = $(this).find("answerchoice2").attr("value");
	            usersession.answerchoice3 = $(this).find("answerchoice3").attr("value");
	            //usersession.answerchoice4 = $(this).find("answerchoice4").attr("value");
	            usersession.correctanswer = $(this).find("correctanswer").attr("value");
	            usersession.questionimage = $(this).find("questionimage").attr("value");
	            usersession.correctresponsetitle = $(this).find("correctresponsetitle").attr("value");
	            usersession.correctresponsebody = $(this).find("correctrepsonsebody").attr("value");
	            usersession.correctresponseimage = $(this).find("correctrepsonseimage").attr("value");
	            usersession.incorrectresponsetitle = $(this).find("incorrectresponsetitle").attr("value");
	            usersession.incorrectresponsebody = $(this).find("incorrectrepsonsebody").attr("value");
	            usersession.incorrectresponseimage = $(this).find("incorrectrepsonseimage").attr("value");	            
	            //testvars();
	            /*if(typeof rememberme!="undefined"){
	                setcookie(usersession.email,password);
	            }*/
	            switch(action){
	                case "register":					
	                    registered();										
	                    break;
	                case "login":						
	                    loggedin();						
	                    break;
	            }
				break;			
		}
    });
}

function setcookie(email,password){
    deletecookies();
	//alert("pass: " + password);
    $.cookie(cookiename, "true", cookieoptions);
    $.cookie("email", email, cookieoptions);
    $.cookie("password", password, cookieoptions);
}

function deletecookies(){
    $.cookie(cookiename, null);
    $.cookie("email", null);
    $.cookie("password", null);
}

//Added for testing
function testvars(){
    var msg = ""
    for (var i in usersession)
    {
        msg = msg + "usersession." + i + " is " + usersession[i] + "\r\n";
    }
    alert(msg);
}

function submitreg(){
	if(validateandshow())
	{
		_hbPageView('sweepsPage-submitRegistrationForm-click','/');
	    htmlpost(pathtoproxy+registerpage,"register","","","","#frmsubmitreg");
	}	
}

function submitstf(){
    htmlpost(pathtoproxy+sendtofriendpage,"stf","","","","#frmsubmitstf");
}
function submitfp(){
	_hbPageView('sweepsPage-forgotPasswordRequestSendButton-click','/');
   htmlpost(pathtoproxy+passwordrequestpage,"fp","","","","#frmforgotpassword");
}

function registerme(){	
	prizePanelOpen = false;
	_hbPageView('sweepsPage-openRegistrationForm-click','/');
	loadhtml("register.html","showregister","#content","",0,0,"","#registrationpage");
}

function registered(){
    togglelogin("welcome");
    loadhtml("register-confirmation.html","registerconfirm","#content","",0,0,"","#registerconfirm");
}

function loggedin(){
    togglelogin("welcome");
    if(usersession.questioncompleted=="0"){		
        loadhtml("welcomeback.html","welcomeback","#content","",0,0,"","#welcomeback");
    }else{		
        loadhtml("alreadyanswered.html","alreadyanswered","#content","",0,0,"","#alreadyanswered");
    }
}

function logout(){
	_hbPageView('sweepsPage-logout-click','/');
    htmlpost(pathtoproxy+logoutpage,"logout","sessionid=" + usersession.sessionid + "&email=" + usersession.email,"","","#frmlogout");
    delete usersession;
    delete usersession.sessionid;
    delete usersession.questioncompleted;
	deletecookies();
    hidecontent();
    loadhtml("welcome.html","showlogout","#content","",0,0,"","#welcome");	
    togglelogin("login");
    if($("#whitebox").css("left")=="-540px"){
        showit(".map-txt",false);
        $("#whitebox").animate({"left":"34px"}, animatespeed);
    }
}

function submitanswer(answer){	
	isanswersubmitted = 1;	
	var uemail =escape(usersession.email);	
	uemail = uemail.replace("@","%40");	
    htmlpost(pathtoproxy+submitanswerpage,"answer","sessionid=" + usersession.sessionid + "&email=" + uemail + "&answer=" + answer,"",answer,"#submitanswer");
}

function login(rememberme){
	_hbPageView('sweepsPage-loginInfoFormLoginButton-click','/');
    animateflags("up",false);
    var data;
	if(rememberme!=null){
		setcookie($("#welcome1-in").val(), $("#welcome2-in").val());
	}
    if($.cookie(cookiename)=="true" && $.cookie("email")!=null && $.cookie("password")!=null){	
       data = "email=" + $.cookie("email") + "&password=" + $.cookie("password");	   
    }else{
       data = $("#frmlogin").serialize();			   
    }			
    htmlpost(pathtoproxy+loginpage,"login",data,rememberme,"","#frmlogin");
}

function showlogin(){    
	prizePanelOpen = false;
    if(flagsactive){animateflags("up",false);}
    
    if($("#whitebox").css("left")=="-540px"){
        showit(".map-txt",false);
        $("#whitebox").animate({"left":"34px"}, animatespeed);
    }	
    loadhtml("login.html","showlogin","#content","",0,0,"","#loginpage");
}

function tryquestion(){
	_hbPageView('sweepsPage-answerTodaysQuestionButton-click','/');
    toggletagline("login");
    loadquestion();
}

function loadquestion(top,left){		
	var leftpx = parseInt(parseInt(usersession.questionlocationleft) - 60) + "px";
	var toppx = parseInt(parseInt(usersession.questionlocationtop)) + "px";	
    loadhtml("question.html","tryquestion","#q-stripe","",toppx,leftpx);
}

function togglelogin(status){
    if(status=="login"){
        $("#usern").html("Already registered? <a><img class='rollover' src='images/loginsm_off.gif' border='0' onclick='showlogin();' alt='Login' /></a>");
		$("a").hover(
	        function(){
			    $(this).addClass("cursorstate");
	        },
	        function(){
	            $(this).removeClass("cursorstate");
	        }
		);
		showit("#login",true);
    } else if(status=="welcome"){
            $("#usern").html("Welcome, " + usersession.firstname + "<a><img class='rollover' src='images/logout_off.gif' onclick='logout()' alt='Logout'/></a>");
			showit("#login",true);
    } else {
        $("#usern").html("");
		showit("#login",false);
    }
}

function showit(objid,status,top,left){   	    
	if($(objid).css("display") == "none" && !status)
	{
	  return;
	}	
    if(status){
        if(objid=="#prizeboxcont" || objid=="#q-stripe"){				
			var mtop =0;			
			if(top)
			{
               mtop = top.replace("px","");
			}
			
			var mleft =0;
			if(left)
			{
               mleft = left.replace("px","");
			}
            $(objid).css("visibility","visible");	
			if(objid=="#prizeboxcont")
			{
				$(objid).show("scale", {origin:[mtop-60,mleft]}, 1000,function(){$("#gall-back").css("display","inline");
										$("#gall-back").css("visibility","visible");	
										$("#gall-next").css("display","inline");
										$("#gall-next").css("visibility","visible");	
									
										if(currentflag == 1)
										{
											$("#gall-back").css("visibility","hidden");	
											$("#gall-back").css("display","none");	
										}
										if(currentflag == 5)
										{
											$("#gall-next").css("visibility","hidden");		
											$("#gall-next").css("display","none");
										}});	           
			}
			else
			{
				$(objid).show("scale", {origin:[mtop-60,mleft]}, 1000);	           
			}	
        }else{	      

			switch(objid)
			{
				case "#tosbox":
					$("#flashqmarkercont").css("z-index","9");
					closecont("#emailfbox");					
					closecont("#fpassbox");
					closecont("#fpasssuccessbox");
					break;
				case "#emailfbox":
					$("#flashqmarkercont").css("z-index","9");
					closecont("#tosbox");	
					closecont("#fpassbox");
					closecont("#fpasssuccessbox");
					break;
			}
		
            $(objid).css('visibility','visible');
            $(objid).fadeIn(fadespeed);					
            $(objid).css('display','block');
        }
    }else{	            
        closecont(objid,top,left);
    }	
}

function closecont(objid,top,left){ 
    if((objid=="#prizeboxcont" || objid=="#q-stripe") && top){
        $(".sweepstakes").removeClass("quiz");
            var mtop = 0;
            if(top)
            {
                  mtop = top.replace("px","");
            }
            var mleft=0;
            if(left)
            {
                  mleft = left.replace("px","");
            }
			$(objid).hide("scale", {origin:[mtop-60,mleft]}, 1000);
    }else{               
       switch(objid)
       {        
        case "#tosbox":
            $("#login").css("visibility","hidden");
            break;
        case "#emailfbox":
            $("#login").css("visibility","visible");
            break                        
        case "#fpassbox":
            $("#login").css("visibility","visible");
            break;
        case "#errorbox":
			if($("#loginpage").css("visibility") != "visible")
			{
	            $("#login").css("display","block");
	            $("#login").css("visibility","visible");
			}
            break;
        case ".all-sweepstakes":
				  $(".all-sweepstakes").css("display","none");					
				  $(".logo-bl").css("display","block");					
				  $(".logo-bl").css("visibility","visible");					
                  $(".map-txt").css("visibility","hidden");
                  animatemarker("up");
                  animateflags("up",false);
                  break;
        }
        $(objid).fadeOut(fadespeed);
    }
}

function loadflags(){	
	$("#close-q").click();
	if (flagsloaded && (!prizePanelOpen)) {	   		
		animateflags("down",true);	
		if($("#whitebox")){$("#whitebox").animate({"left":"-540px"}, animatespeed);}
		$("#login").css("display","block");
		$("#login").css("visibility","visible");
		$("#emailfbox").css("visibility","hidden");
		$("#tosbox").css("visibility","hidden");					
		$("#clickhere").css("visibility","hidden");
	    $("#clickhere").css("display","none");		
		if(usersession && usersession.sessionid)
		{			
			$('#trivia-q').css("visibility","visible");
			$('#trivia-q').css("display","block");
		}
		else
		{
		   $('#reg-b').css("visibility","visible");
		   $('#reg-b').css("display","block");
		}
		$('.logo-bl').css("visibility","visible");
		$('.logo-bl').css("display","block");	
		$('#login').css("visibility","visible");
		$('#login').css("display","block");	
		$('#rolle').css("visibility","visible");
		$('#rolle').css("display","block");	
		if(typeof usersession!="undefined"){
			if(usersession.questioncompleted=="1"){                    
				$('#trivia-q').css("visibility","hidden");
			}
		}

		return;
	}			
    hidecontent();    
	flagsloaded = true;	
	animateflags("down",true);	
	if(usersession && usersession.sessionid)
	{					
	    $('#trivia-q').css("visibility","visible");
	    $('#trivia-q').css("display","block");
	}
	else
	{
	   $('#reg-b').css("visibility","visible");
	   $('#reg-b').css("display","block");
	}
	$('.logo-bl').css("visibility","visible");
	$('.logo-bl').css("display","block");	
	$('#login').css("visibility","visible");
	$('#login').css("display","block");	
	$('#rolle').css("visibility","visible");
	$('#rolle').css("display","block");	
    if(typeof usersession!="undefined"){
        if(usersession.questioncompleted=="1"){                    
            $('#trivia-q').css("visibility","hidden");
        }
    }
}

function tryq() {
    hidecontent("tryq");
    if(typeof usersession=="undefined"){
        registerme();
    }else{    	    
	    $(".map-txt").css("visibility","visible");
	    $(".map-txt").css("display","block");	    
	    $("#clickhere").css("visibility","visible");
	    $("#clickhere").css("display","block");
	    $('.logo-bl').css("visibility","visible");		    
	    animatemarker("down");	                 	    	         
	    $("#whitebox").animate({"left":"-540px"}, animatespeed);
	    $("#whitebox").css("display","block");
    }
}

function animatemarker(status){   
    $(".qmarker").css("background","url(images/qs.gif)");
    if(status=="down")
	{                
		$(".pin-1").css("left",(parseInt(usersession.questionlocationleft)+10) + "px");
		$(".pin-1").css("top",(parseInt(usersession.questionlocationtop)+162) + "px");
        markeractive = true;
		$("#flashqmarkercont").css("z-index","9");
		$(".pin-1").css("z-index","500");
        mypin.animateDown();
    }else{                                
        markeractive = false;
		mypin.animateUp();
		$("#flashqmarkercont").css("z-index","-100");
    }
}

function animateflags(status,showmaptxt){ 

    if(showmaptxt && ($(".map-txt").css("visibility")=="hidden" || $(".map-txt").css("display")=="none")){showit(".map-txt",true);}		
    var position = "";
    if(status=="down"){        
        if($("#whitebox")){$("#whitebox").animate({"left":"-540px"}, animatespeed);}
        position = "+";
        flagsactive = true;
        if(markeractive){
            animatemarker("up");
        }
		$("#flashflagcont").css("z-index","9");		
        delayit('myflag[1].animateDown();',0);
        delayit('myflag[2].animateDown();',250);
        delayit('myflag[3].animateDown();',500);
        delayit('myflag[4].animateDown();',750);
        delayit('myflag[5].animateDown();',1000);
    }else{
        flagsactive = false;
        myflag[1].animateUp();		
        myflag[2].animateUp();		
        myflag[3].animateUp();		
        myflag[4].animateUp();
        myflag[5].animateUp();
		delayit('$("#flashflagcont").css("z-index","-100");',750);		
    }
}

function opengallery(flagnum){
    getprizes(flagnum);
}

function loadprize(flagnum,top,left){
  if(($("#emailfbox").css("display") == "none" || $("#emailfbox").css("visibility") == "hidden") && ($("#fpassbox").css("display") == "none" || $("#fpassbox").css("visibility") == "hidden"))
   {
	currentflag=flagnum;		
	if (prizePanelOpen) return;
	_hbPageView('sweepsPage-PrizeGallery-open','/');
	prizePanelOpen = true;
	if (imagespreloaded == false) {
		$("#ajaxloading").css('visibility','visible').fadeIn(0);
		loadPrizePause1 = flagnum;
		loadPrizePause2 = top;
		loadPrizePause3 = left;
		setTimeout("loadPrizePause()", 500);
		return;
	}
    if(flagnum==6){
        flagnum=1;
    }else if(flagnum==0){
        flagnum=5;
    }	
	var mtop = parseInt(parseInt($(".flag" + flagnum + "-1").css("top").replace("px","")) -245) + "px";
	var mleft = $(".flag" + flagnum + "-1").css("left");
    loadhtml("prize.html","prize","#prizeboxcont",flagnum,mtop,mleft);
   }	
}
function loadPrizePause() {
	if (imagespreloaded == true) {
		loadprize(loadPrizePause1,loadPrizePause2,loadPrizePause3);
	} else {
		setTimeout("loadPrizePause()", 500);
	}
}

function delayit(exp,delay){    
    setTimeout(exp,delay);
}

function XMLtoString(elem){
	var serialized;
	try {
		// XMLSerializer exists in current Mozilla browsers
		serializer = new XMLSerializer();
		serialized = serializer.serializeToString(elem);
	} 
	catch (e) {
		// Internet Explorer has a different approach to serializing XML
		serialized = elem.xml;
	}
	return serialized;
}

function loadPrizeObjects() {
	if($("#prizeoverflow").html()=="") {			
		if(!imagespreloaded) {
			preloadimages();
		}
	}	
}
function ajaxHourglass(sState) {
	switch (sState) {
		case "on":
			$().ajaxSend(function(r,s,m){ 	        
				$("#ajaxloading").css('visibility','visible').fadeIn(0);
			});
			$().ajaxStop(function(r,s){    		        
				$("#ajaxloading").css('visibility','visible').fadeOut(500);
			});
		break;
		case "off":
			$().ajaxSend(function(r,s,m){ 	        
				$("#ajaxloading").css('visibility','visible').fadeOut(0);
			});
			$().ajaxStop(function(r,s){    		        
				$("#ajaxloading").css('visibility','visible').fadeOut(0);
			});
		break;
	}
}

function pausecomp(millis)
{
	var date = new Date();
	var curDate = null;
	do { curDate = new Date(); }
	while(curDate-date < millis);
} 

function validateRegistration(postdata) {
	var paramTemp = postdata.split("&")
	var retTemp = "";
	for (var j=0; j<paramTemp.length; j++) {
		switch (j) {
			case 0: //firstname
				if (paramValue(paramTemp[j])=="First+name") {
					retTemp += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;First name<br/>"
				}
			break;
			case 1: //lastname
				if (paramValue(paramTemp[j])=="Last+name") {
					retTemp += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Last name<br/>"
				}
			break;
			case 2: //businessname
				if (paramValue(paramTemp[j])=="Business+name+(optional)") {
					//not required
				}
			break;
			case 3: //street
				if (paramValue(paramTemp[j])=="Street") {
					retTemp += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Street<br/>"
				}
			break;
			case 4: //city
				if (paramValue(paramTemp[j])=="City") {
					retTemp += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;City<br/>"
				}
			break;
			case 5: //state
				if (paramValue(paramTemp[j])=="State") {
					retTemp += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;State<br/>"
				}
			break;
			case 6: //zip
				if (paramValue(paramTemp[j])=="Zip+code") {
					retTemp += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Zip code<br/>"
				}
			break;
			case 7: //phone
				if (paramValue(paramTemp[j])=="Phone+number") {
					retTemp += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Phone number<br/>"
				}
			break;
			case 8: //email
				if (paramValue(paramTemp[j])=="E-mail") {
					retTemp += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;E-mail<br/>"
				}
			break;
			case 9: //password
				if (paramValue(paramTemp[j])=="Password") {
					retTemp += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Password<br/>"
				}
			break;
			case 10: //shipinfo
				if (paramValue(paramTemp[j])=="shipinfo") {
					//not required
				}
			break;
			case 11: //sendreminders
				if (paramValue(paramTemp[j])=="sendreminders") {
					//not required
				}
			break;
		}
	}
	if (retTemp.length > 0) {
		retTemp = "Please enter the following:<br/><br/>" + retTemp
	}
	return retTemp;
}
function paramValue(sParam) {
	return sParam.substr(sParam.indexOf("=")+1);
}
function hidePanelsForBottomLinks() {
	hidecontent('closeprize');				
	$("#prizeboxcont").css("visibility","hidden");
	$(".map-txt").css("display","block");				
	$('#rolle').css("visibility","visible");	
	$('.map-txt').css("visibility","visible");				
	$("#flashqmarkercont").css("z-index","-100");
}
function trackMe(query) {
    // Native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();

    // ActiveX XMLHttpRequest object
    } else if (window.ActiveXObject) {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (request) {
        request.onreadystatechange = function() { 
            return false; 
        };
        request.open("get", "images/trackingpixel.gif", true);
		request.send(query);
    }
	return false;
}
function removeField(sPostdata, sField) {
	var iIndex1 = sPostdata.indexOf(sField);
	var iIndex2 = sPostdata.indexOf("&", iIndex1);
	alert(sPostData);
	var sSnip = sPostData.substr(iIndex1, iIndex2 - iIndex1);
	alert(sSnip);
}

function setMaxLength(field,stringvalue,length)
{  
  if(stringvalue.indexOf(field.value) == -1)
  {	
    if(field.value.length > length)
	{
	  var e = window.event ? event.keyCode : evt.which;
	  field.value = field.value.substring(0,length);
	}
  }
}

function onloginenter(event)
{	
	evt = event || window.event;
	var keycode = evt.which || evt.keyCode;	
	if(keycode==13)
	{
		login($('#remember:checked').val());
	}	
}	