var changed = false;
function fieldChanged()
{
	changed = true;
}

var saving = false;
function CheckFlagSave()
{
	var retVal = saving;
	if(!saving)
	{
		saving = true;

		if(document.getElementById("bmg")!=null)
		{
			document.getElementById("bmg").style.visibility = "hidden";
			document.getElementById("bmg").style.height = "1px";
			document.getElementById("bmg").style.overflow = "hidden";	
		}
		
		var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
		
		var divTag = document.getElementById("divsave"); 
		if(divTag==null)
		{
			var divTagBG = document.createElement("div");
			divTagBG.style.margin = "0px auto"; 
			divTagBG.style.position = "absolute";
			divTagBG.style.top = '0px';
			divTagBG.style.left = '0px';
			divTagBG.id = "divsavebg";
			divTagBG.innerHTML = "<iframe style=\"height:" + arrayPageSize[1] + "px;width:" + arrayPageSize[0] + "px\" src=\"\"></iframe>";
			document.body.appendChild(divTagBG);
			
			divTag = document.createElement("div");
			divTag.id = "divsave"; 
			divTag.style.margin = "0px auto"; 
			divTag.style.position = "absolute";
			
			//divTag.style.top = '100px';
			//divTag.style.left = (((arrayPageSize[0] - 20 - 240) / 2) + 'px');

			divTag.style.top = '0px';
			divTag.style.left = '0px';
			
			divTag.style.height = arrayPageSize[1] + 'px';
			divTag.style.width = arrayPageSize[0] + 'px';

			divTag.className ="divsave";
			
			divTag.innerHTML = "<table height=\"100%\" width=\"100%\" cellpadding=\"10\" cellspacing=\"10\"><tr><td align=\"center\" valign=\"top\"><div style=\"width:400px\" id=\"savemsg\">Processing, please wait a few moments...<br/><br/><img src='images/loading1.gif' /></div></td></tr></table>";
			document.body.appendChild(divTag);		
			
			window.scroll(0,0);
		}
	}
	
	return retVal;
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}


function FlagSaveFailed()
{
	saving = false;
	
	if(document.getElementById("bmg")!=null)
	{
		document.getElementById("bmg").style.visibility = "visible";	
		document.getElementById("bmg").style.height = "auto";
		document.getElementById("bmg").style.overflow = "auto";	
	}
	
	var divTagBG = document.getElementById("divsavebg");
	if(divTagBG!=null)
	{
		divTagBG.parentNode.removeChild(divTagBG);
	}
	
	var divTag = document.getElementById("divsave");
	if(divTag!=null)
	{
		divTag.parentNode.removeChild(divTag);
	}
}

function OpenWindow(url, name, width, height)
{
	var options = "scrollbars=yes,width=" + width + ",height=" + height;
	var myWindow = window.open(url, name, options);
	myWindow.focus();
}

function allocationTypeChange()
{
	//Allocation modes:
	//1: advertiser allocates funds
	//2: skupe net allocates funds
	if(document.advertiserForm.allocationMode[0].checked)
	{
		document.getElementById("meAllocate").className = "generaltextbold";
		document.getElementById("autoAllocate").className = "generaltext";
		document.getElementById("autobudget").style.visibility = "hidden";
		if(document.getElementById("budgetsRow")!=null) document.getElementById("budgetsRow").style.visibility = "visible";
	}
	else
	{
		document.getElementById("meAllocate").className = "generaltext";
		document.getElementById("autoAllocate").className = "generaltextbold";
		if(document.advertiserForm.allocationBudgetDisplay!=null)
		{
			document.advertiserForm.allocationBudget.value = document.forms[0].allocationBudgetDisplay.value;
		}
		else
		{
			document.advertiserForm.allocationBudget.value = "0.00";
		}
		document.getElementById("autobudget").style.visibility = "visible";
		if(document.getElementById("budgetsRow")!=null) document.getElementById("budgetsRow").style.visibility = "hidden";
	}
	
	document.getElementById("savebut").style.visibility = "visible";
	fieldChanged();
}

function BudgetFieldChange()
{
	fieldChanged();
	document.getElementById("savebut").style.visibility = "visible";
}

function TextAreaChanged(field, fieldLen, divElemName)
{
	var divElement = document.getElementById(divElemName);
	
	if(fieldLen>=field.value.length)
	{
		divElement.innerHTML="[" + (fieldLen-field.value.length) + "]";
	}
	else
	{
		divElement.innerHTML="<font color=\"red\">[" + (fieldLen-field.value.length) + "]</font>";
	}
	fieldChanged();
}

function ChangeProfile(pLocation)
{
	var myForm = document.forms[0];
	if(changed)
	{
		if(confirm("Do you wish to save your changes before leaving screen?\nOK to continue with saving\nCANCEL to continue without saving"))
		{
			if(myForm.submitted!=null) myForm.submitted.value = "true";
			myForm.navigateTo.value=pLocation;
			myForm.submit();
		}
		else
		{
			document.location.href=pLocation;
		}
	}
	else
	{
		document.location.href=pLocation;
	}
}

function Navigate(pScreen, pLocation)
{
	var myForm = document.forms[0];
	var newUrl = pLocation;
	
	if(pLocation.indexOf("navigate.do")==-1)
	{
		newUrl = "navigate.do?method=changeScreen&newScreen=" + escape(pScreen) + "&newScreenLink=" + escape(pLocation);
	}
	
	if(changed)
	{
		if(confirm("You are about to lose all unsaved changes. Are you sure you wish to continue?\nOK to continue without saving\nCANCEL to return"))
		{
			document.location.href=newUrl;
		}
	}
	else
	{
		document.location.href=newUrl;
	}
}

function Reset()
{
	var myForm = document.forms[0];
	if(changed)
	{
		if(confirm("Are you sure you wish to cancel all your changes?"))
		{
			myForm.reset();
			changed = false;
		}
	}
	else
	{
		myForm.reset();
		changed = false;
	}
}

var currenciesValid = true;
function ValidateCurrency(field)
{
	var reCurrency = /^\d+\.\d{2}$/;

	if ((field.value=="undefined") || (field.value==""))
	{
		field.value="0.00";
	}
	else
	{
		if(field.value.indexOf(".")==-1)
		{
			field.value += ".00";
		}
		else if(field.value.indexOf(".")==(field.value.length-1))
		{
			field.value += "00";
		}
		else if(field.value.indexOf(".")==(field.value.length-2))
		{
			field.value += "0";
		}
		
		if(!reCurrency.test(field.value))
		{
			currenciesValid = false;
			alert("Invalid currency value entered!");
			field.focus();
		}
		else
		{
			currenciesValid = true;
		}
	}
}

function ValidatePublisherDetails()
{
	if(CheckFlagSave()) return false;
	
	if(!currenciesValid)
	{
		FlagSaveFailed();
		return false;
	}

	var sError = "";

	if((document.publisherDetailsForm["publisherDetails.username"].value=="undefined") || (document.publisherDetailsForm["publisherDetails.username"].value==""))
	{
		sError += "Please enter your username!\n";
	}

	if((document.publisherDetailsForm["publisherDetails.password"].value=="undefined") || (document.publisherDetailsForm["publisherDetails.password"].value==""))
	{
		sError += "Please enter your password!\n";
	}
	else
	{
		if(document.publisherDetailsForm["publisherDetails.password"].value!=document.publisherDetailsForm["confirmPassword"].value)
		{
			sError += "Your confirm password does not match your password!\n";
		}
	}
		
	if((document.publisherDetailsForm["publisherDetails.siteUrl"].value=="undefined") || (document.publisherDetailsForm["publisherDetails.siteUrl"].value==""))
	{
		sError += "Please enter your site url!\n";
	}
	
	if ((document.publisherDetailsForm["publisherDetails.siteDescription"].value=="undefined") || (document.publisherDetailsForm["publisherDetails.siteDescription"].value==""))
	{
		sError += "Please enter a description of your site!\n";
	}
	else
	{
		if(document.publisherDetailsForm["publisherDetails.siteDescription"].value.length>5000)
		{
			sError += "Description of your site cannot be greater than 5000 characters!\n";
		}
	}
	
	if((document.publisherDetailsForm["publisherDetails.trafficDesc"].value=="undefined") || (document.publisherDetailsForm["publisherDetails.trafficDesc"].value==""))
	{
		sError += "Please enter some details about the amount of traffic your site gets!\n";
	}

	if(sError!="")
	{
		FlagSaveFailed();
		alert(sError);
		return false;
	}
	else
	{
		return true;
	}
}

function ValidatePublisherOffersDetails()
{
	if(CheckFlagSave()) return false;
	
	if(!currenciesValid)
	{
		FlagSaveFailed();
		return false;
	}
	
	var sError = "";
	
	var premiumWebAndPrintSelected = false;
	var professionalWebAndPrintSelected = false;
	
	var i=0;
	for(i=0;i<checkBoxes.length;i++)
	{
		if(checkBoxes[i].id.indexOf("offerImg_14_")!=-1 && checkBoxes[i].src.indexOf("offerOn")!=-1)
		{
			premiumWebAndPrintSelected = true;
		}
		
		if(checkBoxes[i].id.indexOf("offerImg_16_")!=-1 && checkBoxes[i].src.indexOf("offerOn")!=-1)
		{
			professionalWebAndPrintSelected = true;
		}
	}
	
	if(premiumWebAndPrintSelected && professionalWebAndPrintSelected)
	{
		sError += "You cannot select both web and print packages. Please select an offer under either Premium OR Professional.\n";
	}

	/*if((parseFloat(document.publisherOffersForm["publisherDetails.budget"].value)>0.0) && (parseInt(getSelectedRadioValue(document.publisherOffersForm["publisherDetails.selectedOffer.offerId"]))==-1))
	{
		FlagSaveFailed();
		alert("Please select the offer you wish to allocate your daily budget to.");
		return false;
	}*/
	
	/*if((parseFloat(document.publisherOffersForm["publisherDetails.budget"].value)==0.0) && (parseInt(getSelectedRadioValue(document.publisherOffersForm["publisherDetails.selectedOffer.offerId"]))>0))
	{
		alert("Please enter the daily budget to allocate to the offer you have selected.");
		return false;
	}*/
	
	if(sError!="")
	{
		FlagSaveFailed();
		alert(sError);
		return false;
	}
	else
	{
		return true;
	}
}

function ValidateAdvertiserDetails()
{
	if(CheckFlagSave()) return false;
	
	var sError = "";

	if((document.advertiserDetailsForm["advertiserFullDetails.advertiserUserDetails.password"].value=="undefined") || (document.advertiserDetailsForm["advertiserFullDetails.advertiserUserDetails.password"].value==""))
	{
		sError += "Please enter your password!\n";
		document.advertiserDetailsForm["advertiserFullDetails.advertiserUserDetails.password"].className="validationfailed2";
	}
	else
	{
		if(document.advertiserDetailsForm["advertiserFullDetails.advertiserUserDetails.password"].value!=document.advertiserDetailsForm["confirmPassword"].value)
		{
			sError += "Your confirm password does not match your password!\n";
			document.advertiserDetailsForm["advertiserFullDetails.advertiserUserDetails.password"].className="validationfailed2";
			document.advertiserDetailsForm["confirmPassword"].className="validationfailed2";
		}
		else
		{
			document.advertiserDetailsForm["advertiserFullDetails.advertiserUserDetails.password"].className="validationok";
			document.advertiserDetailsForm["confirmPassword"].className="validationok";	
		}
	}
		
	if ((document.advertiserDetailsForm["advertiserFullDetails.advertiserUserDetails.companyDesc"].value!="undefined") && (document.advertiserDetailsForm["advertiserFullDetails.advertiserUserDetails.companyDesc"].value!=""))
	{
		if(document.advertiserDetailsForm["advertiserFullDetails.advertiserUserDetails.companyDesc"].value.length>5000)
		{
			sError += "Description of your company cannot be greater than 5000 characters!\n";
			document.advertiserDetailsForm["advertiserFullDetails.advertiserUserDetails.companyDesc"].className="validationfailed2";
		}
		else
		{
			document.advertiserDetailsForm["advertiserFullDetails.advertiserUserDetails.companyDesc"].className="validationok";
		}
	}
	else
	{
		document.advertiserDetailsForm["advertiserFullDetails.advertiserUserDetails.companyDesc"].className="validationok";
	}
	
	var bAtLeastOneContactWithEmail = false;
	if (document.getElementById("contactcontainer") != null)
	{
		var cells = document.getElementById("contactcontainer").getElementsByTagName("div");
		for (var i = 0; i < cells.length; i++) { 
		    var contId = cells[i].getAttribute("id");
		    if(contId.indexOf("contacttable_")!=-1)
		    { 
		    	contId = contId.substring(13);
		    	
		    	var contactTable = document.getElementById("contacttable_" + contId);
				if(contactTable.style.visibility != "hidden")
				{
			    	var field1 = document.advertiserDetailsForm["contactField(email_" + contId + ")"];
			    	var field2 = document.advertiserDetailsForm["contactField(phone_" + contId + ")"];
			    	
			    	if((field1.value=="undefined" || field1.value=="") && (field2.value=="undefined" || field2.value==""))
			    	{
			    		sError += "You must enter either a phone number or an email address for each contact!\n";
						field1.className="validationfailed2";
						field2.className="validationfailed2";
			    	}
			    	else
			    	{
			    		field1.className="validationok";
						field2.className="validationok";
			    	}
			    	
			    	if(!bAtLeastOneContactWithEmail && !(field1.value=="undefined" || field1.value==""))
			    	{
			    		bAtLeastOneContactWithEmail = true;
			    	}
			    }
		    }
		}
	}
	
	//if(!bAtLeastOneContactWithEmail)
	//{
	//	sError += "You must have at least one contact and at least one of your contacts must have an email address!\n";
	//}
	
	//if(bPaymentMethodsAvailable && parseInt(getSelectedRadioValue(document.advertiserDetailsForm["advertiserDetails.selectedPaymentMethod"]))==-1 )
	//{
	//	sError += "Please select how you wish to pay!\n";
	//}

	if(sError!="")
	{
		FlagSaveFailed();
		alert(sError);
		return false;
	}
	else
	{
		return true;
	}
}

function getSelectedRadioValue(radioGroup)
{
	var selectedIndex = -1;
	for (i=radioGroup.length-1; i>-1; i--)
	{
		if (radioGroup[i].checked)
		{
			selectedIndex = i;
		}
	}

	if (selectedIndex != -1)
		return radioGroup[selectedIndex].value;
	else
		return "-1";
}

setTimeout("clearMessages()",5000);
function clearMessages()
{
	var messageselem = document.getElementById("messageselem");
	if(messageselem!=null)
	{
		messageselem.style.display = "none";
		messageselem.style.visibility = "hidden";
	}
}



//====================================================================
//    URLEncode and URLDecode functions
//
//Copyright Albion Research Ltd. 2002
//http://www.albionresearch.com/
//
//You may copy these functions providing that 
//(a) you leave this copyright notice intact, and 
//(b) if you use these functions on a publicly accessible
//  web site you include a credit somewhere on the web site 
//  with a link back to http://www.albionresearch.com/
//
//If you find or fix any bugs, please let us know at albionresearch.com
//
//SpecialThanks to Neelesh Thakur for being the first to
//report a bug in URLDecode() - now fixed 2003-02-19.
//And thanks to everyone else who has provided comments and suggestions.
//====================================================================
function URLEncode(pIn)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = pIn;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                     + ch 
                     + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}

function URLDecode(pIn)
{
// Replace + with ' '
// Replace %xx with equivalent character
// Put [ERROR] in output if %xx is invalid.
var HEXCHARS = "0123456789ABCDEFabcdef"; 
var encoded = pIn;
var plaintext = "";
var i = 0;
while (i < encoded.length) {
    var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
return plaintext;
}

function Validate_String(string, return_invalid_chars)
{
	valid_chars = '1234567890-_.^~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	invalid_chars = '';
	if(string == null || string == '')
		return(true);

	//For every character on the string.   
	for(index = 0; index < string.length; index++)
	{
		char = string.substr(index, 1);                        
  
		//Is it a valid character?
		if(valid_chars.indexOf(char) == -1)
		{
			//If not, is it already on the list of invalid characters?
			if(invalid_chars.indexOf(char) == -1)
			{
				//If it's not, add it.
				if(invalid_chars == '')
					invalid_chars += char;
				else
					invalid_chars += ', ' + char;
			}
		}
	}
         
	//If the string does not contain invalid characters, the function will return true.
	//If it does, it will either return false or a list of the invalid characters used
	//in the string, depending on the value of the second parameter.
	if(return_invalid_chars == true && invalid_chars != '')
	{
		last_comma = invalid_chars.lastIndexOf(',');
		if(last_comma != -1)
			invalid_chars = invalid_chars.substr(0, $last_comma) + ' and ' + invalid_chars.substr(last_comma + 1, invalid_chars.length);
		return(invalid_chars);
	}
	else
		return(invalid_chars == ''); 
}

function Validate_Email_Address(email_address)
{
	//Assumes that valid email addresses consist of user_name@domain.tld

	at = email_address.indexOf('@');
	dot = email_address.indexOf('.');

	if(at == -1 || 
		dot == -1 || 
		dot == 0 || 
		dot == email_address.length - 1)
	{
		return(false);
	}
  
	user_name = email_address.substr(0, at);
	domain_name = email_address.substr(at + 1, email_address.length);                  

	if(Validate_String(user_name) === false || Validate_Url(domain_name, 0) === false)
	{
		return(false);
	}

	return(true);
}

function Validate_Url(theurl, withPrefix) {
	var tomatch;
	if (withPrefix == 0)
		tomatch= /^[A-Za-z0-9\.-]{2,}\.[A-Za-z]{2,}$/;
	else
		tomatch= /^(http(s){0,1}:\/\/){0,1}[A-Za-z0-9\.-]{2,}\.[A-Za-z]{2,}$/;
    if (tomatch.test(theurl))
    {
        return true;
    }
    else
    {
        return false; 
    }
}
