var windowwidth;
var windowheight;
var browsertype;
var userplatform;
var printwin=null;
var ajaxinsertdiv;
var whitespace = " \t\n\r";
var activeuser;
var hosturlholder_clean;
var hosturlholder_exact;
var alertmessage;
var min_age = 21;

//GETS THE USERS BROWSERS AND SETS A GLOBAL VARIABLE
function getbrowser(){
	
  if (navigator.appName.toLowerCase() == 'netscape'){
      browsertype="netscape";
	  userplatform = navigator.platform;
	  if (navigator.platform.toLowerCase() == 'iphone'){
	  	userplatform = 'iphone';
	  }
  }
  
  if (navigator.appName.toLowerCase() == 'microsoft internet explorer'){
      browsertype="ie";
	  userplatform = navigator.platform;
  }
  
  //alert('Browser: '+browsertype+'\nPlatform: '+userplatform)
  
}

function checkurl(){
	
	if (location.search != ""){
		var x = location.search.substr(1).split(";")
		for (var i=0; i<x.length; i++)
		{
			var y = x[i].split("=");
			//alert("Key '" + y[0] + "' has the content '" + y[1]+"'")
		}		
		parseurlargs(y);
	}else{
		//alert('No URL arguments found');
	}
	
}

// Check whether string s is empty.
function isEmpty(s)
{ return ((s == null) || (s.length == 0)) }

function isWhitespace(s){
	var i;
	
	// Is s empty?
	if (isEmpty(s)) return true;
	
	// Search through string's characters one by one
	// until we find a non-whitespace character.
	// When we do, return false; if we don't, return true.
	
	for (i = 0; i < s.length; i++)
	{
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
	
		if (whitespace.indexOf(c) == -1) return false;
	}
	
	// All characters are whitespace.
	return true;
}

function hasWhiteSpace(s)
{
 
     reWhiteSpace = new RegExp(/^\s+$/);
 
     // Check for white space
     if (reWhiteSpace.test(s)) {
          alert("Please Check Your Fields For Spaces");
          return false;
     }
	
	return true;
}

function DoCallback(url,params)
{
	var pageUrl=url+"?callback=true&param="+params;
	var xmlRequest=createXMLHttp();
	xmlRequest.open("POST",pageUrl,false);
	xmlRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	xmlRequest.send('');
	return xmlRequest;
}

function createXMLHttp(){
	if(typeof XMLHttpRequest!="undefined"){
		return new XMLHttpRequest();
	}else if(window.ActiveXObject){
		var aVersions=["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp","Microsoft.XMLHttp"];
		for(var i=0;i<aVersions.length;i++){
			try{var xmlRequest=new ActiveXObject(aVersions[i]);
			return xmlRequest}catch(oError){}
		}
	}throw new Error("XMLHttp object could be created.");
}

function getwinsize(){
	
	if(!browsertype){
		getbrowser();
	}
	
	if(browsertype=="netscape"){
		windowwidth = window.innerWidth;
		windowheight = window.innerHeight;
	}
	
	if(browsertype=="ie"){
		windowwidth = document.documentElement.clientWidth;
		windowheight = document.documentElement.clientHeight;
	}
	
}

function printimage(imagepath){
	
		printwin = window.open();
		self.focus();
		printwin.document.open();
		printwin.document.write('<'+'html'+'><'+'head'+'><'+'/'+'head'+'><'+'body'+'>');
		printwin.document.write('<img src="'+imagepath+'" border="0" />');
		printwin.document.write('<'+'/'+'body'+'><'+'/'+'html'+'>');
		printwin.document.close();
		printwin.print();
		printwin.close();
		
}

function makeHttpRequest(url, callback_function, return_xml, xmlelement, insertdiv){
	
//alert(url +'\n'+ callback_function +'\n'+ return_xml +'\n'+ xmlelement +'\n'+ insertdiv);
	
 var http_request, response, i; 
 
 ajaxinsertdiv = '';

 var activex_ids = [ 
   'MSXML2.XMLHTTP.3.0', 
   'MSXML2.XMLHTTP', 
   'Microsoft.XMLHTTP' 
 ]; 

 if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+... 
   http_request = new XMLHttpRequest(); 
   if (http_request.overrideMimeType) { 
     http_request.overrideMimeType('text/xml'); 
   } 
 } else if (window.ActiveXObject) { // IE6 and older 
   for (i = 0; i < activex_ids.length; i++) { 
     try { 
       http_request = new ActiveXObject(activex_ids[i]); 
     } catch (e) {} 
   } 
 } 

 if (!http_request) { 
   alert('Unfortunately your browser doesn\'t support this feature.'); 
   return false; 
 } 

 http_request.onreadystatechange = function() { 
   if (http_request.readyState !== 4) { 
       // not ready yet 
       return; 
   } 
   if (http_request.status !== 200) { 
     // ready, but not OK 
     //alert('There was a problem with the request.(Code: ' + http_request.status + ')'); 
     return; 
   }
   
   if(insertdiv){
		ajaxinsertdiv = insertdiv;
   }
		
   if (return_xml) { 
     response = http_request.responseXML;
	 
	 if(xmlelement != ''){
		var snippethtml = response.getElementsByTagName(xmlelement)[0].firstChild.nodeValue;	 
		callback_function(snippethtml);
	 }else{
		// invoke the callback 
   		callback_function(response); 	 
	 }
	 
   } else { 
     	response = http_request.responseText;
	 	// invoke the callback 
   		callback_function(response); 
   } 
   
 }; 

 http_request.open('GET', url, true); 
 http_request.send(null); 
}


function replaceajax(responsetext){
	
	var ajdiv = document.getElementById(ajaxinsertdiv);
	//var newNode = document.createTextNode(responsetext);
	
	ajdiv.innerHTML = responsetext;
	
	var expander = hs.getExpander(ajdiv);
    expander.reflow();
		
}


function addjspage(pagename){
	
	var pageid = pagename;
	var filename = './inc/' + pagename + '.js';
	//alert(filename);
	var headTag = document.getElementsByTagName('head')[0]; 
	script = document.createElement('script'); 
	script.id = pageid; 
	script.type = 'text/javascript'; 
	script.src = filename; 
	headTag.appendChild(script);
	
}

function makeRequest(url) {  
  makeHttpRequest(url, displaycontent);  
}


function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}


function getcontrols(whichl){
	
	//alert(whichl);
	
	switch(whichl){
		case 'gcslim_wedit':
			makeHttpRequest('http://www.cplanet.com/cpajax/cplayouts.xml', setcpcontrols, true, 'gcslim_wedit');
		break;
		
		case 'gcslimwhite':
			makeHttpRequest('http://www.cplanet.com/cpajax/cplayouts.xml', setcpcontrols, true, 'gcslimwhite');
		break;
		
		case 'cpcontrols':
			makeHttpRequest('http://www.cplanet.com/cpajax/cplayouts.xml', setcpcontrols, true, 'cpglobalcontrols');
		break;
		
		case 'cpsfcontrols':
			makeHttpRequest('http://www.cplanet.com/cpajax/cplayouts.xml', setcpcontrols, true, 'cpglobalsfcontrols');
		break;
		
		case 'cpcontrolsfb':
			makeHttpRequest('http://www.cplanet.com/cpajax/cplayouts.xml', setfacebookapp, true, 'gcslimfb_wedit');
		break;
		
		case 'cpcontrols_simple':
			makeHttpRequest('http://www.cplanet.com/cpajax/cplayouts.xml', setcontrolssimple, true, 'cpglobalcontrols');
		break;
		
		case 'cpglobalcontrols_wsearch':
			makeHttpRequest('http://www.cplanet.com/cpajax/cplayouts.xml', setcpcontrols, true, 'cpglobalcontrols_wsearch');
		break;
	}
}

function logoutButton_Click() {
	Sys.Services.AuthenticationService.logout(hosturlholder_exact, null, errorCallback);
}

function errorCallback(error) {
	//alert("This is the error: " + error.get_message());
}

function setcontrolssimple(rethtml){
	document.getElementById("cpcontrols").innerHTML = rethtml;
}

function cleanurl(urlstring){
	
	var unicodechar_amps = "%26";
	var unicodechar_ques = "%3f";
	var NewURLString1 = urlstring.replace(/&/, unicodechar_amps);
	var NewURLString2 = NewURLString1.replace('?', unicodechar_ques);
	
	return NewURLString2
}

function cleanquotes(textstring){
	
	var unicodechar = "/'";
	var NewURLString = textstring.replace(/'/, unicodechar);
	
	return NewTextString
}

function setcpcontrols(rethtml){
	//alert(rethtml);
	document.getElementById("cpcontrols").innerHTML = rethtml;
	
	hosturlholder_clean = cleanurl(window.location.href);
	
	try{
		activeuser = document.getElementById("HiddenFieldloggedonusername").value;
	}catch(err){
		activeuser = 'nouser';	
	}
	
	if(activeuser != 'nouser' && activeuser!= ""){
		 document.getElementById("loglinkholder").innerHTML = '<a href="javascript:logoutButton_Click()">Log Out</a>';
		 document.getElementById("cpuserholder").innerHTML = "<b>Welcome " + activeuser + "</b>";
		 document.getElementById("passportlinkholder").innerHTML = '<a href="http://www.cplanet.com/passport.aspx" class="globalcontrolsstyle" >My Passport</a>';
		 
		 try{
			checkforeditmode();
		 }catch(err){
			 //NO ACTION 
		 }
		 
	}else{
		document.getElementById("loglinkholder").innerHTML = '<a href="http://www.cplanet.com/cplogin_fb.aspx?ReturnToHost='+hosturlholder_clean+'">Log In</a>';
	}
}

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 setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

function checkCookie(){
	username=getCookie('username');
	if (username!=null && username!=""){
	  //alert('Welcome again '+username+'!');
	}else{
		getalertinfo();
	}
}

function getalertinfo(){
	try{
		var infostring = document.getElementById("HiddenFieldAlertInfo").value;
		var valuestring = infostring.split("|");
		
		if(valuestring.length == 11){
			var alerttype = valuestring[0];
			var agetoverify = valuestring[1];
		}
		
		//alert(alerttype +' - '+ agetoverify);
		switch(alerttype){
			case 'ALERT':
				buildalertmessage('alert');
				//highslideajax('cpajax/cpsnippets.html', 'ageverify', 'ajaxanchor', 'AGE VERIFICATION', '650', '350', true);
			break;
			
			case 'AGREE':
				buildalertmessage('agree');
				//highslideajax('cpajax/cpsnippets.html', 'ageverify', 'ajaxanchor', 'AGE VERIFICATION', '650', '350', true);
			break;
			
			case 'AGE VERIFICATION':
				if(agetoverify != ""){
					min_age = parseInt(agetoverify);
				}
				makeHttpRequest('cpajax/cplayouts.xml', buildageverifyalert, true, 'ageverify');
				//highslideajax('cpajax/cpsnippets.html', 'ageverify', 'ajaxanchor', 'AGE VERIFICATION', '650', '350', true);
			break;
		}
		
	}catch(err){
		//NO ACTION	
	}
		
}

function buildalertmessage(messagetype){
	
	var custommessage = document.getElementById("HiddenFieldAlertMessage").value;
	var alertbutton;
	
	if(custommessage != ""){
		if(messagetype == 'alert'){
			alertbutton = '<div align="center"><input type="button" name="btnAlertMessage" value="Enter" onClick="wasalerted()"></div>';
		}else{
			alertbutton = '<div align="center"><input type="button" name="btnAlertMessage" value="I Agree" onClick="wasalerted()"></div>';	
		}
	
		document.getElementById("alertmessagediv").innerHTML = custommessage + alertbutton;
		
		highslidecontrol('alertmessage');
	}
	
}

function wasalerted(){
	var randomnum = Math.floor(Math.random()*11111111)
	var username = randomnum;
	setCookie('username',username,30);
	closeactiveexpander();
}

function buildageverifyalert(agehtml){
	
	var ageverifyhtml;
	var custommessage = document.getElementById("HiddenFieldAlertMessage").value;
	
	if(custommessage == ""){
		custommessage = '<div align="center" class="cpfontheading">You must be '+min_age+' to enter</div><div align="center" class="cpfonttitle">'+document.getElementById("HiddenDestinationName").value+'</div>';
	}
	
	ageverifyhtml = '<div align="center" style="padding:20px; display:table-cell; vertical-align:middle;">' + custommessage + agehtml + '</div>';
	
	document.getElementById("alertmessagediv").innerHTML = ageverifyhtml;
	
	highslidecontrol('alertmessage');
	//displayMessage(ageverifyhtml, 'AGE VERIFICATION', '600', '250')
	
}

function requestenter(){
	var oktoenter;
	
	oktoenter = checkAge();
	if(oktoenter == true){
		var year = document.getElementById("year").value;
		var month = document.getElementById("month").value;
		var day = document.getElementById("day").value;
		var randomnum = Math.floor(Math.random()*1111)
		var username = year+month+day+randomnum
		setCookie('username',username,30);
		closeactiveexpander();
	}else{
		alert("Sorry, you are not old enough to enter this storefront.");
		window.location.href = "http://www.cplanet.com";
	}
}

function checkAge(){
	/* change "age_form" to whatever your form has for a name="..." */
	var year = parseInt(document.getElementById("year").value);
	var month = parseInt(document.getElementById("month").value) - 1;
	var day = parseInt(document.getElementById("day").value);
	
	//alert(year +' - '+ month +' - '+ day);

	var theirDate = new Date((year + min_age), month, day);
	var today = new Date;
	
	var realage = (today.getTime() - theirDate.getTime());
	
	if(realage){
		if (realage < 0) {
			//alert("You are too young to enter this site!");
			return false;
		}
		else {
			return true;
		}
	}else{
		alert("No valid birthday found");
		return false;
	}
}


