/* common javascript functions */


// function GUnload is called but does not appear to exist
function GUnload() {
}

// SwapImage - swap a particular image with another..
function SwapImage(Image, NewSrc)
{
	// set the new src
	Image.src = NewSrc;
}

function IsUsingIE() {
	if(navigator.userAgent.indexOf('MSIE') > -1) return true;
	else return false;
}

// activates the submit button when the terms and conditions tick box has been selected...
function EnableSubmit(element, SubmitClass)
{
	// if there is a value for the element.. enable the submit button..
	if (element.checked)
	{
		document.getElementById('ActivateSubmit').disabled = false;
//		document.getElementById('ActivateSubmit').setAttribute("class", SubmitClass);
		document.getElementById('ActivateSubmit').className = SubmitClass;
	}
	// else, do nothing..
	else
	{
		document.getElementById('ActivateSubmit').disabled = true;
//		document.getElementById('ActivateSubmit').setAttribute("class", SubmitClass.concat(" disabled_button"));
		document.getElementById('ActivateSubmit').className = SubmitClass.concat(" disabled_button");
	}
}


// ensures that traffic is simulated properly when using the ajax search results..
function TrafficMeasurement()
{
	// update the ad spots..
//	var URL = '/?Action=refresh_banner&BannerType=top';
//	new Ajax.Updater('heading_banner', URL, {evalScripts:true});
//	var URL = '/?Action=refresh_banner&BannerType=side';
//	new Ajax.Updater('side_banner', URL, {evalScripts:true});
}




/* confirm the proper entry of the password into the lost password form */
function ConfirmPasswordEntry()
{
	// if the password entry field is blank
	if (document.getElementById('password_entry').value.trim() == '')
	{
		document.getElementById('password_error_message').style.display = 'block';
		return false;
	}
	else
	{
		return true;
	}
}


// string trim function
String.prototype.trim = function() 
{
	return this.replace(/^\s+|\s+$/g,"");
}


/* modal_window.js */

// setup the modal window by creating the required divs
function SetupAjaxThrobber() 
{
//	return; 
	
	// get all elements within the body tag - get the first
	var bod = window.top.document.getElementsByTagName('body')[0];
	
	// create the overlay
	var overlay = window.top.document.createElement('div');
	overlay.id = 'throbber_overlay';

	// create the modal window
	var lb = window.top.document.createElement('div');
	lb.id = 'throbber_pane';
	lb.innerHTML = '<p><img src="/images/throbber/throbber.gif" /><b>Loading, please wait ...</b></p>';

	// append them to the body
	bod.appendChild(overlay);
	bod.appendChild(lb);
}

// display the throbber window
function ShowThrobber()
{
	return;
	
	// show..
	SwitchThrobberPane('block');
}

function SwitchThrobberPane(Mode)
{
//	return;
	if (window.top.document.getElementById('throbber_overlay'))
		window.top.document.getElementById('throbber_overlay').style.display = Mode;
	if (window.top.document.getElementById('throbber_pane'))
		window.top.document.getElementById('throbber_pane').style.display = Mode;
}

// hide the modal window
function HideThrobber()
{
	return;
	
	// hide
	SwitchThrobberPane('none');
}

// is the throbber hidden?
function ThrobberHidden()
{
//	return (1);
	
	return (document.getElementById('throbber_overlay').style.display == 'none');
}



// display the throbber window
function ShowImageUploadThrobber()
{
//	return;
	
	// show..
	SwitchThrobberPane('block');
}

// hide the modal window
function HideImageUploadThrobber()
{
//	return;
	
	// hide
	SwitchThrobberPane('none');
}


function UpdateDiv(Div, URL)
{
	// show the ajax throbber
	ShowThrobber();
	
	// handles the on success state
	var handlerfunc = function(t)
	{			
		setTimeout(function() 
		{
			// hide the ajax throbber
			HideThrobber();
		}, 500);
	}
	
	new Ajax.Updater(Div, URL, {evalScripts:true,onSuccess:handlerfunc});
}

function UpdateTabbedSelection(NewSearchID, Div, URL, RadioOptions, Prefix)
{
	// show the ajax throbber
	ShowThrobber();
	
	// handles the on success state
	var handlerfunc = function(t)
	{			
		setTimeout(function() 
		{
			// set the radio fields..
			var Options = RadioOptions.split(',');
			for(i=0; i<Options.length; i++)
			{
				var FieldId = Prefix+Options[i];
				
				// update the radio buttons (if they exist)
				if (document.getElementById(FieldId))
				{
					var Element = document.getElementById(FieldId);

			    	if(NewSearchID==Options[i])
						Element.checked = 1;
					else
						Element.checked = 0;
				}
			}

			// hide the ajax throbber
			HideThrobber();
		}, 100);
	}
	
	new Ajax.Updater(Div, URL, {evalScripts:true,onSuccess:handlerfunc});
}


function UpdateHomePageSearch(NewSearchID, Div, URL)
{
	UpdateTabbedSelection(NewSearchID, Div, URL, "1,2", "home_page_search_radio_");
}

function UpdateProfileSelect(NewSearchID, Div, URL)
{
	UpdateTabbedSelection(NewSearchID, Div, URL, "SIGNUP,LOGIN", "profile_select_radio_");
}

function UpdateReviewSelect(NewSearchID, Div, URL)
{
	UpdateTabbedSelection(NewSearchID, Div, URL, "LATEST,SEARCH", "review_select_radio_");
}

/*
   Written by Jonathan Snook, http://www.snook.ca/jonathan
   Add-ons by Robert Nyman, http://www.robertnyman.com
 */

function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}


function getElementsByAttribute(attribute, oElm, strTagName, strAttributeValue){

	var arrElements = (strTagName == "*" && document.all) ? document.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strAttributeValue = strAttributeValue.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)");
	var oElement;

	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.getAttribute(attribute))){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

function SetFieldError(fieldIds)
{
	//fieldIds is a comma seperated list of fields.
	var Fields = fieldIds.split(',');

	//for each field..
	for(var i=0; i<Fields.length; i++)
	{
		thisFieldId = Fields[i];
		
		//Get the actual field element so we can modify it!
		var Field = document.getElementById(thisFieldId);

		if(Field)
		{
			ChangeClass(Field, 'error_field');

			//Get the label that relates to the field.
			var Label = getElementsByAttribute('for', document, 'label', thisFieldId);
			Label = Label.pop();
			if(Label)
				ChangeClass(Label, 'error_label');
		}
	}
}

function ChangeClass(Field, Class)
{
	if(Field.className && Field.className!='undefined')
		Field.className += ' ' + Class;
	else
		Field.className = Class;
}

//Field Ids is a comma seperated list of fields to update.
//LiItem.title is a comma seperated list of values to update the fields with.
function AutoCompleteUpdateField(LiItem, FieldIds)
{
    ValueParts = LiItem.title.toString().split(',');
	FieldParts = FieldIds.toString().split(',');

	for(var i = 0; i < ValueParts.length; i++)
	{
		if(FieldParts[i])
		{
			document.getElementById(FieldParts[i]).value = ValueParts[i];
		}
	}
}

// Toggles between the two states on the sitemap page
function SitemapSearchesToggle(DivID)
{
	Effect.toggle(DivID, 'blind');
}

// ProcessCommentInput - function to process the actual comment input
function ProcessCommentInput(ListingFunc, ListDivId, FieldDivId)
{
	document.getElementById(ListDivId).style.display = 'block';

	var URL = 'index.htm?Action=lookup_data&ListingFunc=' + ListingFunc + '&ListDivId=' + ListDivId+ '&FieldDivId=' + FieldDivId;

	new Ajax.Updater(ListDivId, URL, {});
	return "";
}

// hides the drop down matches listing
function HideLookupListing(ListingID) {
	document.getElementById(ListingID).style.display = 'none';
}


function SetCommentValue(ListingID, FieldID, Comment)
{
	var Current = document.getElementById(FieldID);
	insertAtCaret(Current, Comment);
	HideLookupListing(ListingID);
	document.getElementById(FieldID).focus();
}



// MaskAlphaInput 
// function to ensure that alpha input does not make its way into the selected field
function MaskAlphaInput(e)
{
	// setup the characters that we are allowing
	var allow = '1234567890';
	
	// setup the handler for the key press
	var k = document.all ? parseInt(e.keyCode): parseInt(e.which);

	// if the key pressed is not in the allowed list, return false, otherwise return true
	// also allow backspace (8) and delete, arrows etc...
	return (   (allow.indexOf(String.fromCharCode(k)) != -1) || (k == 8) || (k == 0)   );
}

// MaskAlphaInputForPrice
// function to ensure that alpha input except . does not make its way into the selected field
function MaskAlphaInputForPrice(e)
{
	// setup the characters that we are allowing
	var allow = '1234567890.';

	// setup the handler for the key press
	var k = document.all ? parseInt(e.keyCode): parseInt(e.which);

	// if the key pressed is not in the allowed list, return false, otherwise return true
	// also allow backspace (8) and delete, arrows etc...
	return (   (allow.indexOf(String.fromCharCode(k)) != -1) || (k == 8) || (k == 0)   );
}

function MaskAlphaInputForKeywords(e)
{
	// setup the characters that we are allowing
	var allow = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,- ,.';

	// setup the handler for the key press
	var k = document.all ? parseInt(e.keyCode): parseInt(e.which);

	// if the key pressed is not in the allowed list, return false, otherwise return true
	// also allow backspace (8) and delete, arrows etc...
	return (   (allow.indexOf(String.fromCharCode(k)) != -1) || (k == 8) || (k == 0)   );
}


/*
//myField accepts an object reference, myValue accepts the text strint to add
function InsertAtCursor(myField, myValue)
{
	//IE support
	if (document.selection)
	{
		myField.focus();

		// in effect we are creating a text range with zero
		// length at the cursor location and replacing it
		// with myValue
		sel = document.selection.createRange();
		sel.text = myValue;

		alert(sel.id);
		
//		myField.value = sel.text;
//		sel.text = '';
	}

	//Mozilla/Firefox/Netscape 7+ support
	else if (myField.selectionStart || myField.selectionStart == '0')
	{
		//Here we get the start and end points of the
		//selection. Then we create substrings up to the
		//start of the selection and from the end point
		//of the selection to the end of the field value.
		//Then we concatenate the first substring, myValue,
		//and the second substring to get the new value.
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)+ myValue+ myField.value.substring(endPos, myField.value.length);
	}
	else
	{
		myField.value += myValue;
	}
}
*/

function insertAtCaret(obj, text)
{ 
	if(document.selection) 
	{ 
		obj.focus(); 
		var orig = obj.value.replace(/\r\n/g, "\n"); 
		var range = document.selection.createRange(); 
	 
		if(range.parentElement() != obj) 
		{ 
			return false; 
		}
	 
		range.text = text; 
	         
		var actual = tmp = obj.value.replace(/\r\n/g, "\n"); 
	 
		for (var diff = 0; diff < orig.length; diff++) 
		{ 
			if(orig.charAt(diff) != actual.charAt(diff)) break; 
		} 
	 
		for (var index = 0, start = 0; tmp.match(text) && (tmp = tmp.replace(text, "")) && index <= diff; index = start + text.length) 
		{ 
			start = actual.indexOf(text, index); 
		} 
	} 
	else if(obj.selectionStart) 
	{ 
		var start = obj.selectionStart; 
		var end   = obj.selectionEnd; 
	 
		obj.value = obj.value.substr(0, start) + text  + obj.value.substr(end, obj.value.length); 
	} 
	     
	if(start != null) 
	{ 
		setCaretTo(obj, start + text.length); 
	} 
	else 
	{ 
		obj.value += text; 
	} 
} 
	 
function setCaretTo(obj, pos) 
{ 
	if(obj.createTextRange) 
	{ 
		var range = obj.createTextRange(); 
		range.move('character', pos); 
		range.select(); 
	} 
	else if(obj.selectionStart) 
	{ 
		obj.focus(); 
		obj.setSelectionRange(pos, pos); 
	} 
}







// This code was written by Tyler Akins and has been placed in the
// public domain.  It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}

function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}




// get the current time stamp
function GetTimeStamp()
{
	var Stamp = new Date();
	var Year = Stamp.getYear();
	var Month = Stamp.getMonth();
	var Day = Stamp.getDate();
	var Hours = Stamp.getHours();
	var Mins = Stamp.getMinutes();
	var Secs = Stamp.getSeconds();
	
	return (Year + '-' + Month + '-' + Day + ' ' + Hours + ':' + Mins + ':' + Secs);
}


// Advertising code
apnpageNum = Math.round(Math.random() * 100000000);

function show_ad_tag(apnadserver,site,classification_type,classification,page_type,ad_size,keyword,pos)
{
	// set the tag to be nothing..
	var Tag = '';
	// get the tag..
	Tag = get_ad_tag(apnadserver,site,classification_type,classification,page_type,ad_size,keyword,pos);
	// if there is an ad tag, output it.
	if (Tag != '')
		document.write('<script src="' + Tag + '"></script>');
}

function get_ad_tag(apnadserver,site,classification_type,classification,page_type,ad_size,keyword,pos)
{
	var Tag = '';
	// Cache-busting and pageid values
	apnrandom = Math.round(Math.random() * 100000000);
	//if (!apnpageNum) var apnpageNum = Math.round(Math.random() * 100000000);
	apntarget = "/SITE=" + site + "/AREA=" + classification_type + "." + classification + "." + page_type + "/AAMSZ=" + ad_size
	if (keyword.length) apntarget = apntarget + "/KEYWORD=" + keyword;
	if (pos.length) apntarget = apntarget + "/POS=" + pos;
	if ( (classification_type.length > 0) && (classification.length > 0) )
	{
		Tag = apnadserver + '/jserver' + apntarget + '/acc_random=' + apnrandom +  "/pageid=" + apnpageNum;
	}
	return (Tag);
}


// remove all children from a particular dom node
function removeChildrenFromNode(node)
{
	if (node == undefined || node == null)
	{
		return;
	}

	var len = node.childNodes.length;

	while (node.hasChildNodes())
	{
		node.removeChild(node.firstChild);
	}
}


/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
function echeck(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    alert("Invalid E-mail ID")
	    return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	    alert("Invalid E-mail ID")
	    return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    alert("Invalid E-mail ID")
	    return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	    alert("Invalid E-mail ID")
	    return false
	 }
	
	 if (str.indexOf(" ")!=-1){
	    alert("Invalid E-mail ID")
	    return false
	 }

	 return true					
}
function validateEmailForm( form ) {
	emailID=form.email.value
	phoneNumber=form.phone.value
	if (emailID && echeck(emailID)==false){
		//alert("The Email address entered " + emailID.value + ' is not valid')
		form.email.value="";
		form.email.focus();
		return false
	}
	if ( phoneNumber=="" || phoneNumber.length<6) {
		alert('Phone number is required (at least 6 digits)');
		form.phone.value="";
		form.phone.focus();
		return false
	}
	return true
}
/* end of file */
