var windowListingUse;
var windowOtherUse;
var windowDemoUse;


//var used throughout the website.
//Values same in pageMageSlice.listings.status
var DRAFT_LISTING_TYPE = 1;
var SCHEDULED_LISTING_TYPE = 2;
var ACTIVE_LISTING_TYPE = 3; //auction.status = 1
var CLOSED_LISTING_TYPE = 4;
var SOLD_LISTING_TYPE  = 5;  //auction.status = 6
var UNSOLD_LISTING_TYPE = 6; //auction.status = 2

var SITE_INFO = '#siteInfo'; //div tag use to store site information
var MISC_INFO = "#miscInfo"; //div tag use to store additional lsiting information.
var IMAGE_UPLOAD_LIMIT = 12; //The maximum image a user can upload.
var REQUIRED_STAR_SRC = "/images/listinginfo/required_star.gif";
var REQUIRED_STAR_IMG = "<img type='requiredStar' src='"+REQUIRED_STAR_SRC+"'>";
var ERROR_STAR_SRC = "/images/listinginfo/error_star.gif";
var ERROR_STAR_IMG = "<img type='errorStar' src='"+ERROR_STAR_SRC+"'>";
var ERROR_STAR = ERROR_STAR_SRC;


//variables used throughout the listing process.
var gbl_paramDID = getURLParam("did");
var gbl_paramAID = getURLParam("aid");
var gbl_paramLISTTYPE = getURLParam("typ");
var gbl_paramFLOW = getURLParam("flw");
var gblTimeout;

//variables for default listing preferences.
var FINISH_1 = "finish1";
var FINISH_2 = "finish2";
var FINISH_3 = "finish3";
var FINISH_4 = "finish4";
var DEFAULT_PAYPAL_EMAIL = "paypalEmail";
var DEFAULT_LOC_CITY = "locationCity";
var DEFAULT_LOC_STATE = "locationState";
var DEFAULT_LOC_ZIP = "locationZip";
var DEFAULT_ITEM_LOCATION = "itemLocation";
var DEFAULT_RECEIVE_NEWSLETTERS = "receiveNewsletters";
var DEFAULT_RECEIVE_EMAILS= "receiveEmails";

//variables used for displaying messages in form
var GOOD_TEXT = "goodTxt";
var ERROR_TEXT = "errorTxt";
var EBAY_FEE_ICON = "ebayFeeIcon";

//Trim Member Functions
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}


/*
* Fixing Firefox behavior : Pressing space bar will make page scroll down.
* The issue is that if a page has a frame the the focus is on the parent.
* Pressing the space bar will remove the parent document. Strange behavior.
* As a result this will keep the child frame always focused.
*/
function firefoxFixFocus(name) {
	var theDoc =  window.document;
	if (theDoc.addEventListener) {
		theDoc.addEventListener('click',function() {
			focusFrame(name);				
		}, false );
	}	
}

/*
* Will focus on the frame named. 
* This is used in relation to the firefox fix.
*/
function focusFrame(name){
	top.frames[name].focus();
}
	

//Keep track if form has changed.
//When user focuses or clicks on an input, that will be considered a change.
var gblFormChanged = false;

function setFormChanged() {
	gblFormChanged = true;	
}

function getFormChanged() {
	return gblFormChanged;	
}

var rootURL;
var rootAPI;
var rootServerName;
//Get the root url
function setSiteInfo(){
	//Get the root URL
	rURL = $(SITE_INFO).attr("rootURL");
	rootURL = rURL
	if (rURL) {
		//There is a root dfined
		rootURL = rURL
	} else {
		//No base
		rootURL = "";		
	}
	
	//Get the root API
	rootAPI = $(SITE_INFO).attr("rootAPI");
	//Get the server name (domain name or ip)
	rootServerName = $(SITE_INFO).attr("serverName");

}

//Calls a jquery method to adjust the body iin jqGloabl.js
function adjustBodyManual() {
	//$("#adjContent").adjustBody();
}

/*
* Open a popup window without any tools
*
* @param	url		The url of the page to open
* @param	name	The name of the pop up window
* @param	scrollBar	true|false of wheter there should be a scroll bar for the window.
*/
function popupWindow(url, name, scrollBar, width, height) {
	if (scrollBar) {
		//have scroll bar
		scrollVar = 1;	
	} else {			
		//no scroll bar
		scrollVar = 0;

	}
		
	if (width!=null) {
		theWidth = ", width="+width+"px";	
	} else {
		theWidth = '';	
	}
	
	if (width!=null) {
		theHeight = ", height="+height+"px";	
	} else {
		theHeight = '';	
	}
	
	if(name=="pmListing") {
		if (windowListingUse && !windowListingUse.closed){
			//Do nothing
			windowListingUse.focus();
		} else {
			windowListingUse = window.open (url,name, "menubar=0, resizable=1,status=0, toolbar=0, location=0, directories=0, scrollbars=1"+theWidth+theHeight); 
		}
		//Allow the window to open before focusing.
		setTimeout( function() { windowListingUse.focus() }, 500);
	} else {
		if (windowOtherUse && !windowOtherUse.closed){
			windowOtherUse.location.href= url;
		}  else {
			
			windowOtherUse = window.open (url,name, "menubar=0, resizable=1,status=0, toolbar=0, location=0, directories=0, scrollbars="+scrollVar+theWidth+theHeight); 
		}
		//Allow the window to open before focusing.
		setTimeout( function() { windowOtherUse.focus(); }, 500);
	}//if(name=="pmListing") {
	
}


//If there were changes made in the form, then it will prompt the user with a message box.
function confirmCancel(title, page, height, width) {
	if (gblFormChanged) {
		popupMessage(title, page, height, width);
		return false;
	} else {
		return true;
	}	
}

/*
* Pop up a message box using thickbox.
*
* @param title		the title to display on the popup window.
* @param page		The page to load from the popMsgs folder
* @param height	the height of the thickbox
* @param width		the width of the thickbox
* @param params	additional paramters to be passed.
*
*/
function popupMessage(title, page, height, width, params) {
	if (params!=null) {
		addParams = "&"+params;	
	} else {
		addParams = "";
	}
	

	gotoURL = "/popMsgs/" +page+"?height="+height+"&width="+width+addParams;
	//use the thickbox function to display message.
	if  (isNullEmpty( $("#TB_ajaxContent").html() ) ) {
		tb_show(title,gotoURL,false);
	} else {
		$.ajax({
			type: "POST",
			url: gotoURL,
			success: function(data, textStatus){ 
				reloadContent(data,width,height);
			},
			error :  function (XMLHttpRequest, textStatus, errorThrown) {
				//Do something
			},
			dataType : "html"
		 });	
		
	}

}




//*********************************************************
/**
* Create a cookie
* 
* @param	name	the name of the cookie
* @param	value	the value of the cookie
* @param	days	the number of days for this cookie to last
**/
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

/**
* Read a cookie
* 
* @param	name	the name of the cookie
**/
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/**
* Delete a cookie
* 
* @param	name	the name of the cookie
**/
function eraseCookie(name) {
	createCookie(name,"",-1);
}
//*********************************************************


// This function disables certain control+key combination
// Currently using to disable copy and paste
function disableCtrlKeyCombination(e){
	//list all CTRL + key combinations you want to disable
	var forbiddenKeys = new Array("a", "n", "c", "x", "v", "j");
	var key;
	var isCtrl;

	if(window.event) {
		key = window.event.keyCode;     //IE
		if(window.event.ctrlKey)
				isCtrl = true;
		else
				isCtrl = false;
	} else {
		key = e.which;     //firefox
		if(e.ctrlKey)
				isCtrl = true;
		else
				isCtrl = false;
	}

	//if ctrl is pressed check if other key is in forbidenKeys array
	if(isCtrl) {
		for(i=0; i<forbiddenKeys.length; i++) {
			//case-insensitive comparation
			if(forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase()){
					return false;
			}
		}
	}
	
	return true;
}


/********************************************************
* Misc Validation
********************************************************/
/*
* Validates a string
*
* @param	str		The string to validate
*
* return 	true | false 
*/
function validateString(str) {
	//Check if string is empty.
	if (str.trim()=="") {
		return false;
	}
	
	return true;
}

/*
* Validates a string representation of a number
*
* @param	num		The string representation of the number
*
* return 	true | false 
*/
function validateNumber(num) {

	//Allow for numbers and dot. (non negative);
	var objRegExp  =  /(^\d\d*\.\d*$)|(^\d\d*$)|(^\.\d\d*$)/;
	
	num = num + ' '; //Change number to string.
  	num = num.trim();
  
  	//check for numeric characters  
  	return(objRegExp.test(num));

}

/*
* Validates a integer
*
* @param	num		The string representation of the number
*
* return 	true | false 
*/
function validateInteger( num ) {
  var objRegExp  = /(^\d\d*$)/;
  num = num + ' '; //Change number to string.
  num = num.trim();
  //check for integer characters
  return objRegExp.test(num);
}



/*
* Validates email
*
* @param	str		The email string to validate
*
* return 	true | false 
*/
function validateEmail(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){	   
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){	   
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){		
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){		
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){		
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){		
		return false
	 }
	
	 if (str.indexOf(" ")!=-1){		
		return false
	 }

	 return true					
} //function validateEmail(str) {


/* Create more info box */
function showMoreInfo(elem){	

	//Remove previous message box
	$("#moreInfoOuterBox").remove();
	
	//Select the message to display
	msgType = $(elem).attr("msg");
	
	//Check for width
	if (  isNotNullEmpty( $(elem).attr("msgWidth") ) ) {
		boxWidth = parseInt($(elem).attr("msgWidth"));
	} else {
		boxWidth = 250;
	}	
					
	msg = getMoreInfoMsg(msgType);
		
	//find the position of the clicked elem
	offset = $(elem).offset();
	//Find the height of the elem.
	height = $(elem).height();
	width = $(elem).width();
	//set the position of the msgbox
		
	//Determine where the location of the box will be so msg will not be cut off outside the window.
	if ($(elem).attr("loc")=="left") {
		//elem is on the left
		leftVal = offset.left;			
	} else {
		//elem is on the right
		leftVal = offset.left+width-boxWidth-10;	
	}
	topVal = offset.top + height;
	//create the messagebox
	$(elem).after("<div id='moreInfoOuterBox' style='z-index:100'><div id='moreInfoInnerBox'><div id='moreInfoBox'></div></div></div>");
	//Format the box
	$("#moreInfoInnerBox").corner("round 8px").parent().css('padding', '2px').corner("round 10px");
	//Insert message
	msgTable = "<table name='table'><tr><td style='text-align:left'>"+msg+"</td><td style='vertical-align:top' name='td'><img src='/images/global/close_icon.gif' onclick='closeMoreInfoBox(this)' align='right'></td></tr></table>";
	$("#moreInfoBox").html(msgTable);
	//show the popup message and hide with fading effect
	$('#moreInfoOuterBox').css({left:leftVal,top:topVal,width:boxWidth});
}



/* Remove the more info box */	
function closeMoreInfoBox(elem) {
	$('#moreInfoOuterBox').remove();
}


/*
 * Date Format 1.2.2
 * (c) 2007-2008 Steven Levithan <stevenlevithan.com>
 * MIT license
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}
		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

/*************************
* Get url paramter
*************************/
function getURLParam( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}



/* Throws a warning before allowing content on the page to be reloaded or the window to be cloased */
var gbl_exitWarning = true;
function noExitWarning() {
	window.onblur = doNothing;
	if (gbl_exitWarning) {
		return "Closing or reloading this window without using the button options on the page will result in loss of data.";
		
	
	}
}

function doNothing() {
	
}


/*
* Get the time of when user last merged their ebay listings.
*
* @param 	timestamp	The timestamp of the time when listing was last merged.
*/
function getLastMerged() {
	//Get the time of the last synced.
	var lastSynced = $("#lastMergedValue").text();
	//Get the server now time when the page loaded
	var nowTime = $(SITE_INFO).attr("serverNowTime");
	var timeElapse =  parseInt(nowTime) - parseInt(lastSynced);
	calculateNewTime(timeElapse)
}



/*
* Increase the timestamp and then recalculate the new time.
* Mainly used with setTimeout.
*
* @param	timestamp	the timestamp of the time to add to
*/
function calculateNewTime(timeElapse){
	newStamp = parseInt(timeElapse) + 60000;
	lastMergedTime = calculateTime(newStamp);
	$("#lastMerged").text(lastMergedTime + " ago.");
	setTimeout("calculateNewTime("+newStamp+")", 60000);
}
/*
* Calculate how much time in hours mins secs given a timestamp
*/
function calculateTime(timestamp) {
	mins = parseInt( (timestamp/(1000*60)) % 60 );
	hours = parseInt( (timestamp/(1000*60*60)) % 24 );
	days = parseInt( timestamp/(1000*60*60*24) );
	
	//Get the sigular/plural of the words.
	timeLeft = "";
	strMins = "";
	strHrs = "";
	strDays = "";
	if (mins == 1) { strMins = " min "; } else { strMins = " mins ";}
	if (hours == 1) { strHrs = " hour "; } else { strHrs = " hours ";}
	if (days == 1) { strDays = " day "; } else { strDays = " days ";}
	
	//Get the correct output for the time left.
	if (days > 0) {
		timeLeft = days + strDays;
	} else if (hours > 0) {
		timeLeft = hours + strHrs;
	} else if (mins > 0) {
		timeLeft = mins + strMins;
	} else {
		timeLeft = " less than a minute ";
	}
	
	return timeLeft;
}


/*
* Check if a value is not null or empty
*
* return true if not empty and false if empty.
*/
function isNotNullEmpty(value) {
        var typeOfStr = typeof value;
        if (typeOfStr == "undefined") {
                return false;
        } else if (typeOfStr == "string" && value=="") {
                return false;
        } else if (typeOfStr == "object" && value==null) {
                return false;
        }  else {
                return true;
        }


}

/*
* Check if a value is null or empty
*
* return true | false. Whether it is null or empty.
*/
function isNullEmpty(value) {
        if ( isNotNullEmpty(value) ) {
                return false;
        } else {
                return true;
        }
}


/*
* See if the elem is checked.
*
* @param elem	checkbox element.
*/
function isChecked(elem) {
	if ( isNotNullEmpty($(elem+":checked").val())) {
		return true;
	} else {
		return false;	
	}
}

/*
* Reload the parent window opender window
*
* @param closePopup	true | false of whether to close the pop up window also.
*/
function reloadOpenerWindow(closePopup) {

	if (window.opener == null || window.opener.closed) {
		//Since the window opener is closed just close the window.
		self.close();
	} else {
		window.opener.location.href = window.opener.location.href;	
		window.opener.focus();
		if (closePopup) {
			self.close();
		}
	}
}

/*
* Load a new page to the window opender and close current window.
*
* @param closePopup	true | false of whether to close the pop up window also.
*/
function loadOpenerWindowAndClose(page) {	
	loadOpenerWindow(page, true);

}

/*
* Load a new page to the window opender and close current window.
*
* @param closePopup	true | false of whether to close the pop up window also.
*/
function loadOpenerWindow(page, closeSelf) {	

	if (window.opener == null || window.opener.closed) {
		//Since the window opener is closed just close the window.
		window.open(page, "_blank");
		
	} else {
		window.opener.location.href = page;	
		window.opener.focus();
	}
	
	if (closeSelf) {
		self.close();
	}
	
}


/*
* Maximize the window to fit the screen.
*/
function maximizeWindow() {
	/*
	BUG BUG Commented out just in case it is called.
	window.moveTo(0,0);
	window.resizeTo(screen.width,screen.height);
	*/
}

function gotoElement(elem) {
	var theTop = $(elem).offset().top;
	$('html,body').animate({scrollTop: theTop}, 500);
}

function gotoTop() {
	window.scrollTo(0,0); 
	return false;
}

function gotoPrevPage() {
	window.location.href = readCookie("prevPage");
}



function URLEncode(url) //Function to encode URL.
{
// 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 = url;
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);
}
}
}

return encoded;
};


 

function URLDecode(url) //function decode URL
{
// Replace + with ' '
// Replace %xx with equivalent character
// Put [ERROR] in output if %xx is invalid.
var HEXCHARS = "0123456789ABCDEFabcdef";
var encoded = url;
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 MM_CheckFlashVersion(reqVerStr,msg){
  with(navigator){
	 var isIE  = (appVersion.indexOf("MSIE") != -1 && userAgent.indexOf("Opera") == -1);
	 var isWin = (appVersion.toLowerCase().indexOf("win") != -1);
	 if (!isIE || !isWin){  
		var flashVer = -1;
		if (plugins && plugins.length > 0){
		  var desc = plugins["Shockwave Flash"] ? plugins["Shockwave Flash"].description : "";
		  desc = plugins["Shockwave Flash 2.0"] ? plugins["Shockwave Flash 2.0"].description : desc;
		  if (desc == "") flashVer = -1;
		  else{
			 var descArr = desc.split(" ");
			 var tempArrMajor = descArr[2].split(".");
			 var verMajor = tempArrMajor[0];
			 var tempArrMinor = (descArr[3] != "") ? descArr[3].split("r") : descArr[4].split("r");
			 var verMinor = (tempArrMinor[1] > 0) ? tempArrMinor[1] : 0;
			 flashVer =  parseFloat(verMajor + "." + verMinor);
		  }
		}
		// WebTV has Flash Player 4 or lower -- too low for video
		else if (userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 4.0;

		var verArr = reqVerStr.split(",");
		var reqVer = parseFloat(verArr[0] + "." + verArr[2]);
  
		if (flashVer < reqVer){
		  if (confirm(msg))
			 window.location = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
		}
	 }
  } 
}

/*
* Convert html tags and code to readable HTML entities.
*/
/*
function htmlentities(texto){
    //by Micox - elmicoxcodes.blogspot.com - www.ievolutionweb.com
    var i,carac,letra,novo='';
    for(i=0;i<texto.length;i++){
        carac = texto[i].charCodeAt(0);
        if( (carac > 47 && carac < 58) || (carac > 62 && carac < 127) ){
            //se for numero ou letra normal
            novo += texto[i];
        }else{
            novo += "&#" + carac + ";";
        }
    }
    return novo;
}
*/
function htmlentities (string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
 
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function get_html_translation_table(table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // %          note: Table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }
    
    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
 
    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }
 
    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
      entities['38']  = '&amp;';
      entities['60']  = '&lt;';
      entities['62']  = '&gt;';
      entities['160'] = '&nbsp;';
      entities['161'] = '&iexcl;';
      entities['162'] = '&cent;';
      entities['163'] = '&pound;';
      entities['164'] = '&curren;';
      entities['165'] = '&yen;';
      entities['166'] = '&brvbar;';
      entities['167'] = '&sect;';
      entities['168'] = '&uml;';
      entities['169'] = '&copy;';
      entities['170'] = '&ordf;';
      entities['171'] = '&laquo;';
      entities['172'] = '&not;';
      entities['173'] = '&shy;';
      entities['174'] = '&reg;';
      entities['175'] = '&macr;';
      entities['176'] = '&deg;';
      entities['177'] = '&plusmn;';
      entities['178'] = '&sup2;';
      entities['179'] = '&sup3;';
      entities['180'] = '&acute;';
      entities['181'] = '&micro;';
      entities['182'] = '&para;';
      entities['183'] = '&middot;';
      entities['184'] = '&cedil;';
      entities['185'] = '&sup1;';
      entities['186'] = '&ordm;';
      entities['187'] = '&raquo;';
      entities['188'] = '&frac14;';
      entities['189'] = '&frac12;';
      entities['190'] = '&frac34;';
      entities['191'] = '&iquest;';
      entities['192'] = '&Agrave;';
      entities['193'] = '&Aacute;';
      entities['194'] = '&Acirc;';
      entities['195'] = '&Atilde;';
      entities['196'] = '&Auml;';
      entities['197'] = '&Aring;';
      entities['198'] = '&AElig;';
      entities['199'] = '&Ccedil;';
      entities['200'] = '&Egrave;';
      entities['201'] = '&Eacute;';
      entities['202'] = '&Ecirc;';
      entities['203'] = '&Euml;';
      entities['204'] = '&Igrave;';
      entities['205'] = '&Iacute;';
      entities['206'] = '&Icirc;';
      entities['207'] = '&Iuml;';
      entities['208'] = '&ETH;';
      entities['209'] = '&Ntilde;';
      entities['210'] = '&Ograve;';
      entities['211'] = '&Oacute;';
      entities['212'] = '&Ocirc;';
      entities['213'] = '&Otilde;';
      entities['214'] = '&Ouml;';
      entities['215'] = '&times;';
      entities['216'] = '&Oslash;';
      entities['217'] = '&Ugrave;';
      entities['218'] = '&Uacute;';
      entities['219'] = '&Ucirc;';
      entities['220'] = '&Uuml;';
      entities['221'] = '&Yacute;';
      entities['222'] = '&THORN;';
      entities['223'] = '&szlig;';
      entities['224'] = '&agrave;';
      entities['225'] = '&aacute;';
      entities['226'] = '&acirc;';
      entities['227'] = '&atilde;';
      entities['228'] = '&auml;';
      entities['229'] = '&aring;';
      entities['230'] = '&aelig;';
      entities['231'] = '&ccedil;';
      entities['232'] = '&egrave;';
      entities['233'] = '&eacute;';
      entities['234'] = '&ecirc;';
      entities['235'] = '&euml;';
      entities['236'] = '&igrave;';
      entities['237'] = '&iacute;';
      entities['238'] = '&icirc;';
      entities['239'] = '&iuml;';
      entities['240'] = '&eth;';
      entities['241'] = '&ntilde;';
      entities['242'] = '&ograve;';
      entities['243'] = '&oacute;';
      entities['244'] = '&ocirc;';
      entities['245'] = '&otilde;';
      entities['246'] = '&ouml;';
      entities['247'] = '&divide;';
      entities['248'] = '&oslash;';
      entities['249'] = '&ugrave;';
      entities['250'] = '&uacute;';
      entities['251'] = '&ucirc;';
      entities['252'] = '&uuml;';
      entities['253'] = '&yacute;';
      entities['254'] = '&thorn;';
      entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}

/*
* Pop up a window for user to select a starting path for creating a listing.
*/
function createNewListing() {
	popupWindow("/listings/createNewListing.jsp", "pmListing");	
}

/*
* Pop up a window for user to select a starting with page design.
*/
function createNewPageDesign() {
	//Opens a blank window first
	popupWindow("", "pmListing");	

	$.ajax({
	   type: "post",
	   url: "/builder/listing",
	   data: "op=search&type=all",
	   dataType: "json",
	   success: function(data){
		   var res = "";
		   if (data.listings.length>0) {
			 res = "&tab=pw";  
		   } 
			window.location.href = "/listings/drafts.jsp";
			//popupWindow("/listings/pageDesign.jsp?tmp=1&flw=1"+res, "pmListing");	
			windowListingUse.location = "/listings/pageDesign.jsp?tmp=1&flw=1"+res;
		},
		error :  function (XMLHttpRequest, textStatus, errorThrown) {
			window.location.href = "/listings/drafts.jsp";
			//popupWindow("/listings/pageDesign.jsp?tmp=1&flw=1", "pmListing");	
			windowListingUse.location = "/listings/pageDesign.jsp?tmp=1&flw=1";
		}
	 });
	
	
}


/*
* Pop up a window for user to select a starting with listing Info.
*/
function createNewListingInfo() {
	window.location.href = "/listings/drafts.jsp";
	popupWindow(rootURL+"/listings/listingInfo.jsp?flw=2", "pmListing");	
}


/*
* Pop up a window for user try out the demo mode.
*/
function demoPageDesign() {
	windowDemoUse = window.open ("/demoPageDesign.jsp","testDrive", "menubar=0, resizable=1,status=0, toolbar=0, location=0, directories=0, scrollbars=1"); 
}

/*
* This will edit the page design given a docId and load the main window to the drafts.
*/
function continuePageDesign(did) {
	popupWindow('/listings/pageDesign.jsp?flw=3&typ=1&did='+did, 'pmListing');
	window.location.href = "/listings/drafts.jsp";
}

function stringToBoolean(value) {
	value = value.toLowerCase();
	if (value=="true") {
		return true;
	} else if (value=="false") {
		return false;
	} 
}

/*
* This will set the message and display the message bar.
*
* @param msg 		the message context found inthe message_bar.properites file
* @rdrURL 		The url to redirect to.
* @cnt			The number of tickets 1 or 2 depending on the redirect.
*/

function displayMessageBar(msg, rdrURL, cnt) {
	
	if (cnt==null) {
		cnt = 1;	
	}
	
	$.ajax({
		type: "POST",
		url: "/ajaxCalls/setMessageBar.jsp",
		data: "msg="+msg+"&cnt="+cnt,
		success: function(data, textStatus){ 
			//will only redirect if url is not empty.
			if ( isNotNullEmpty(rdrURL)) {
				window.location.href = rdrURL;
			} else {
				//reload the current page.
				document.location.href = document.location.href;
			}

		},
		error :  function (XMLHttpRequest, textStatus, errorThrown) {
			//Do something
		},
		dataType : "text"
	 });	
}

/* 
* Set the new window document title
*/
function setWindowTitle(txt) {
	document.title = "Page Mage - " + txt;
	//$("title").html(txt);
	//$("#pageHeadingText").html(txt);
}

function resizeImage(imgElem, maxSize) {
	//var size = maxSize+"px";
	var curImage = new Image();
	curImage.src = $(imgElem).attr("src");
	if (curImage.width > curImage.height) {
		var newheight = (maxSize * curImage.height)/curImage.width;
		$(imgElem).attr("width", maxSize);
		$(imgElem).attr("height", newheight);
	} else {
		var newwidth = (maxSize * curImage.width)/curImage.height;
		$(imgElem).attr("width", newwidth);
		$(imgElem).attr("height", maxSize);
	}
	/*
	imgWidth = $(imgElem).width();
	imgHeight = $(imgElem).height();
	//Determine which side is longer.
	if (imgHeight > imgWidth) {
		$(imgElem).attr("height", maxSize+"px");
	} else {
		$(imgElem).attr("width",maxSize+"px");
	}
*/
	//$(imgElem).crop({x:0, y:0, width:100, height:100,transparentURL:"/images/global/spacer.gif"});


}



/*
* Enable and disable a button and its action
*
* @param action			ENABLE, DISABLE			
* @param	elem				The image element.
* @param onClickAction	The action to take for an onclick action
*/
function enableDisableBtn(action, elem, onClickAction) {
	//Get the image src.
	if ($(elem).length > 0) {
		imgSrc = $(elem).attr("src");
		//Repalce the button src.
		if (action == "DISABLE") {
			newSrc = imgSrc.replace("_off", "_disabled");
			$(elem).parent().unbind("click");
		} else {
			newSrc = imgSrc.replace("_disabled", "_off");
		}
		//Replace the button image.
		$(elem).attr("src", newSrc);
		
		if ( isNotNullEmpty(onClickAction) ) {
			//Clears previsou click events with unbind.
			//Then add new click event to the elem.
			$(elem).parent().unbind("click").click(function() {
				eval(onClickAction);	
			});
			
		}
	}

}

/*
* Turn an elem visibility to hidden or visible
*
* @param	elem	The element to change
* @param	action	hidden | visible
*/
function toggleElemVisibility(elem, action) {
	$(elem).css('visibility', action);
}


/*
* This will use the corners.js and set the div with the marked classes.
*/
function setDivCorners() {
	$('.roundGray').corner(); 	
	$('.roundWhite').corner(); 
}

/*
* Return the crumb flow for the listing process according to the style.
*
* @param style 	They type of crumb to generate.
*/
function setListingProcessCrumb(flow, curPage) {

	
	listCrumbOn = "<img src='/images/listinginfo/crumb_list_on.gif'/>&nbsp;";
	listCrumbOff = "<img src='/images/listinginfo/crumb_list_off.gif'/>&nbsp;";
	designCrumbOn = "<img src='/images/listinginfo/crumb_design_on.gif'/>&nbsp;";
	designCrumbOff = "<img src='/images/listinginfo/crumb_design_off.gif'/>&nbsp;";
	publishCrumbOn = "<img src='/images/listinginfo/crumb_publish_on.gif'/>&nbsp;";
	publishCrumbOff = "<img src='/images/listinginfo/crumb_publish_off.gif'/>&nbsp;";
	shareCrumbOn = "<img src='/images/listinginfo/crumb_share_on.gif'/>&nbsp;";
	shareCrumbOff = "<img src='/images/listinginfo/crumb_share_off.gif'/>&nbsp;";
	theCrumb = "";	

	if (curPage == "list") {
		if(flow==1) {
			//Started with Page Disign.
			theCrumb = designCrumbOn + listCrumbOn + publishCrumbOff + shareCrumbOff;
		} else if(flow==2) {
			//Started with Listing Info
			theCrumb = listCrumbOn + designCrumbOff + publishCrumbOff + shareCrumbOff;
		} else if(flow==4) {
			//Editing LIsting
			theCrumb = listCrumbOn + publishCrumbOff + shareCrumbOff;
		}
	}
	
	if (curPage == "designer") {
		if(flow==1) {
		//Started with Page Disign.
		theCrumb = designCrumbOn + listCrumbOff + publishCrumbOff + shareCrumbOff;
		} else if(flow==2) {
			//Started with Listing Info
			theCrumb = listCrumbOn + designCrumbOn + publishCrumbOff + shareCrumbOff;
		} else if(flow==3) {
			//Editing Page Design
			theCrumb = designCrumbOn + publishCrumbOff + shareCrumbOff;
		} 
	}  
	
	if (curPage == "review") {
		if(flow==1) {
			//Started with Page Disign.
			theCrumb = designCrumbOn + listCrumbOn + publishCrumbOn + shareCrumbOff;
		} else if(flow==2) {
			//Started with Listing Info
			theCrumb = listCrumbOn + designCrumbOn + publishCrumbOn + shareCrumbOff;
		} else if(flow==3) {
			//Editing Page Design
			theCrumb = designCrumbOn + publishCrumbOn + shareCrumbOff;
		} else if(flow==4) {
			//Editing LIsting
			theCrumb = listCrumbOn + publishCrumbOn + shareCrumbOff;
		} else {
			//no flow so user is coming to this page directly.
			theCrumb = publishCrumbOn + shareCrumbOff;
		}
	} 
	
	if (curPage == "share") {
		if(flow==1) {
			//Started with Page Disign.
			theCrumb = designCrumbOn + listCrumbOn + publishCrumbOn + shareCrumbOn;
		} else if(flow==2) {
			//Started with Listing Info
			theCrumb = listCrumbOn + designCrumbOn + publishCrumbOn + shareCrumbOn;
		} else if(flow==3) {
			//Editing Page Design
			theCrumb = designCrumbOn + publishCrumbOn + shareCrumbOn;
		} else if(flow==4) {
			//Editing LIsting
			theCrumb = listCrumbOn + publishCrumbOn + shareCrumbOn;
		}
	} 
	
	
	$(".builderListingCrumb").html(theCrumb);
	
}

/*
* This will stop the browser's default events from triggering. 
* Example : click event - opens href
* Result when stopped : browser won't optn href
*
* @param e = the event trigger.
*/
function stopDefault(e) {
	if (e && e.preventDefault) {
		//Prevent the deafult browser action(W3C)
		e.preventDefault();
	} else {
		//Prevent the deafult browser actin in IE
		window.event.returnValue = false;
	}
	
	return false;
}

/*
* Open a popup window to show the video.
*
* @param videoName	The name of the video to show.
*/
function viewVideo(videoName) {
	
	
	if (videoName == "quickTour") {
		popupWindow('/movies/quickTour.jsp', "_blank", true , 500, 400);
	} else if (videoName == "tutorialBlankPage") {
		popupWindow('/movies/tutorialBlankPage.jsp', "_blank", true , 520, 400);
	} else if (videoName == "tutorialGetStarted") {
		popupWindow('/movies/tutorialGettingStarted.jsp', "_blank", true , 540, 400);
	} else if (videoName == "addVideos") {
		popupWindow('/movies/tutorialYoutube.jsp', "_blank", true , 640, 440);
	} else if (videoName == "multiPage") {
		popupWindow('/movies/tutorialMultiPage.jsp', "_blank", true , 640, 440);
	}
	
}//function viewVideo

/*
* Get the attributes found in the miscInfo div.
*
* @param	attr	The attribute to retrieve.
*/
function getMiscInfo(attr) {
	return $(MISC_INFO).attr(attr);
}


/*
* Slide the content up or down depending on the action.
* slide is a jquery functionality which hides the content.
*
* @param elem	The element 
* @param acation	The action to take UP | DOWN
*/
function slideContent(elem, action) {
	if (action == "UP") {
		$(elem).slideUp(1);
	} else {
		$(elem).slideDown(1);
	}
	
}

/*
* disable and enable option field related to the selected section.
* When the master field is toggled, then the slave fields will act accordingly.
*
* master fields have attributes toggleBox=1 and a name
* slave fields have attribute toggle=name of master
*/
function toggleOptionalFieldsCheckbox(elem) {
	if ($(elem).attr("type") == "checkbox") {
		//Testing for checkbox
		if (elem.checked) {
			action = "";
		}else if ($(elem).css("checked") != null) {
			action = "";
		}else {
			action = "disabled";
		}

	} else {
		//Testing for value
		if ($(elem).val()!="") {
			action = "";
		}else {
			action = "disabled";
		}
	}
	
	
	
	curName = $(elem).attr("name");
	$(":input[toggle="+curName+"]").each(
		function() {
			//$(this).attr("disabled");	
			$(this).attr("disabled",action);
		}
	)
	
}//function toggleOptionalFieldsCheckbox

/*
* Preview the listing in a new window. The listing has to be saved to a cookie rather than to a database
* because this is just a preview and user may not wish to save the data.
*/
function previewListing(useListObject, did, aid, type){	
	var cookie="";
	if(!useListObject) {
		cookie = "ck=1&";
	}
	var urlParam = cookie + "typ=" + type + "&did=" + did + "&aid=" + aid;
	//ck=1 is a flag that listing data is stored in a cookie.			
	popupWindow('listingPreview.jsp?'+urlParam, 'pmPreview', true); 
}

/*
* Preview only the page design.
*/
function previewPageDesign(did){	
	//ck=1 is a flag that listing data is stored in a cookie.			
	popupWindow('/listings/pageDesignPreview.jsp?did='+did, 'pmPreview', true); 
}

/*
* Get the hour and ampm and return a 24 hour format
*
* @param	hour	1-12 representing the time
* @param	ampm	AM | PM representing the time of day
*/
function get24HourTime(hour, ampm) {
	hour = parseInt(hour);
	//Determine the house in 24 hour format
	if (hour==12 && ampm=="AM") {
		//12 midnight
		theHour = 0;
	} else if (ampm=="AM"){
		//Hour for am
		theHour = hour;
	} else if (hour==12 && ampm=="PM"){
		//Hour for am
		theHour = 12;
	} else {
		//Hour for pm
		theHour = hour+12;
	}	
	
	return theHour;
}


/*
* Given an array of data, compare to see if any data in the array is duplicated.
*/
function hasDuplicate(testArray) {
	//compare services to see if there are duplicates.
	while (testArray.length>0) {
		var test = testArray.pop();
		//Loop through the res of the services to see if it matches something
		for(x=0; x<testArray.length; x++){
			if (testArray[x] == test) {				
				return true;
			}
		}
	}//while (domServices.length>0) {	
	return false;
}

function isValueInArray(value, testArray) {
	for(i in testArray) {
		if (testArray[i] == value) {
			return true;	
		}
	}
	return false;
}

/*
* Email the error to customer support.
*
* @param error	The string describing the error
* @param errorType	The error type found in ErrorReportBean.java
* @param did	The document Id
*/
function emailError(errMsg, errorType, did) {
	//Ensure exit warning doesn't show up	
	$.ajax({
		type: "POST",
		url: "/ajaxCalls/emailError.jsp",
		data: "errMsg="+errMsg+"&errType="+errorType+"&did="+did,
		success: function(data, textStatus){ 
			//Do something
		},
		error :  function (XMLHttpRequest, textStatus, errorThrown) {
			//Do something
		},
		dataType : "html"
	 });	
}


/*
* Given the height, will adjust the body to it.
* Note, the content currently has to be larger than 560px.
*
* @param elem		the elem to get the height from
* @param addHeight 	additional height to add to the element height. In case the element is only part of other elements.
* @param minHeight	the minimum height for the contnet to shrink to.
*
*/
function matchContentHeight(elem, addHeight, minHeight) {	
	
	var curHeight = elem.height() + addHeight;
	
	if (curHeight < minHeight) {
		curHeight = minHeight;	
	}
	
	$("#contentBtm").attr("src", "/images/global/content_box_btm_5.jpg");
	$("#contentBody").css("height",curHeight);	

	
	//Adjust the threefourth column size
	$(".threefourthColumn").css("height",curHeight);	
	
	//Adjust the bodyWhite div for full pages.
	$(".whiteBody").css("height",curHeight);	
}


function cancelCheckout() {
	popupMessage("Cancel Plan Selection", "checkoutCancel.jsp", 175, 450) ;	
}


/***********************************************************8
* Listing Info Defulat Preferences
*************************************************************/

/*
* Story values to be used for ajax calls to determine if those calls
* has been completed.
*/
function finishValues() {
	var keys = new Array();
	var completed = new Array();
	var successful = new Array();
	
	/*
	* Add the key value pair to the arrays
	*/
	this.setCompleted = function(key, val) {
		var index = getKeyIndex(key);
		if ( index < 0) {
			//Key doesn't exist so add to arrays.
			addNewKey(key);
		} 
			
		//Set the value
		completed[index] = val;
	}
	
	/*
	* Add the key value pair to the arrays
	*/
	this.setSuccess = function(key, val) {
		//Check to see if key already exists.
		var index = getKeyIndex(key);
		if ( index < 0) {
			//Key doesn't exist so add to arrays.
			addNewKey(key);
		} 
			
		//Set the value
		successful[index] = val;
	
	}
	
	/*
	* Loop through all the keys to see if all of them has been completed.
	*/
	this.isAllCompleted = function() {
		for(i in completed) {
			if (i>=0 && !completed[i]) {
				return false;
			}
		}//for(i in this.keys) {
		return true;
	}//getValue(key) {
		
	/*
	* Return the value matching the given key
	*/
	this.isCompleted = function(key) {
		for(i in keys) {
			if (key == keys[i]) {
				return completed[i];
			}
		}//for(i in this.keys) {
	}//getValue(key) {
		
	/*
	* Return the value matching the given key
	*/
	this.isSuccessful = function(key) {
		for(i in keys) {
			if (key == keys[i]) {
				return successful[i];
			}
		}//for(i in this.keys) {
	}//getValue(key) {
	
	/*
	* Check to see fi the key already exists in the database.
	* 
	* Return the index of the matching key or -1 if none.
	*/
	function getKeyIndex(key) {

		for(i in keys) {
			if (key == keys[i]) {
				return i;
			}
		}//for(i in this.keys) {

		return -1;
	}
	
	/*
	* Add a new key
	*/
	function addNewKey(key) {
		keys.push(key);
		completed.push(false);
		successful.push(false);
	}
	
}//function finishValues() {



function saveDefaultInfo(arrKeyVal, index) {			
	fVals.setCompleted(index, false);
	var paramStr = "";
	//create the string parameter
	for( i in arrKeyVal) {
		if (i==0) {
			paramStr += arrKeyVal[i]
		} else {
			paramStr += "&"+arrKeyVal[i]
		}
	}

	$.ajax({
		type: "POST",
		url: "/ajaxCalls/updateDefaultListing.jsp",
		data: paramStr,
		success: function(data, textStatus){ 
			//alert(key);
			//set the key to flag that ajax has been completed.
			fVals.setCompleted(index, true);
			fVals.setSuccess(index, true);
		},
		error :  function (XMLHttpRequest, textStatus, errorThrown) {
			fVals.setCompleted(index, true);
			fVals.setSuccess(index, false);
		},
		dataType : "html"
	 });
}
		



function createErrorMsg(msg) {
	return "<span class='errorTxt'>"+msg+"</span>";
}

function createGoodMsg(msg) {
	return "<span class='goodMsgs'>"+msg+"</span>";
}


// Delay Plugin for jQuery
// - http://www.evanbot.com
// - © 2008 Evan Byrne
jQuery.fn.delay = function(time,func){
	this.each(function(){
		gblTimeout = setTimeout(func,time);
	});
	
	return this;
};


function XMLTraverse(tree) {
	if(tree.hasChildNodes()) {
			document.write('<ul><li>');
			document.write('<b>'+tree.tagName+' : </b>');
			var nodes=tree.childNodes.length;
			for(var i=0; i<tree.childNodes.length; i++)
					traverse(tree.childNodes(i));
			document.write('</li></ul>');
	}
	else
			document.write(tree.text);
}


function previewSampleDesign(did) {
	//Determine where to redirect the user
	if (window.location.pathname == "/landingSamples.jsp") {
		window.location.href = "/landingSamplesPreview.jsp?did="+did
	} else {
		popupWindow('/samplesPreview.jsp?did='+did, 'pmOther', true);
		
	}
}

function viewPricing() {
	//Determine where to redirect the user
	if (window.location.pathname == "/pmlanding.jsp") {		
		gotoURL= "/landingPricing.jsp";
	} else {
		gotoURL = "/pricing";		
	}
	$("#auctivaLearnMore").attr("href", gotoURL);
	
}

/*
* Redirect to the cant edit listing page.
*/
function cantEditListing() {
	gbl_exitWarning = false;
	window.location.href = "/listings/cantEditListing.jsp";
}


/************************************
* Setting and clearing Form error messages
************************************/
/*
* To accomidate previous calls to display error message.
*/
function displayErrorMsg(elemBefore, beforeMsg, elemAfter, afterMsg, section) {
	displayMessage(elemBefore, beforeMsg, elemAfter, afterMsg, section, "error");
}

/*
* To accomidate previous calls to display error message.
*/
function displayGoodMsg(elemBefore, beforeMsg, elemAfter, afterMsg, section) {
	displayMessage(elemBefore, beforeMsg, elemAfter, afterMsg, section, "good");
}

/*
* Display the error on the page.
*
* @param	elemBefore	The element to add the errorStar in front of.
* @param	elemAfter 	the element to add the error message after.
* @param	error		The error message.
* @param	section The section the element is in. To ensure corrent transversing.
* @param 	type	good | error to determine what color for the text.
*/
function displayMessage(elemBefore, beforeMsg, elemAfter, afterMsg, section, type) {
	var message;
	var classType;
	if (type=="good") {
		classType = GOOD_TEXT;
	} else {
		classType = ERROR_TEXT;
	}

	//Check if there is already an error star or a required star
	if ( isNotNullEmpty(elemBefore) && elemBefore.prev().attr("type") == "requiredStar") {
		//Change the required start to the error star
		elemBefore.prev().attr("src", ERROR_STAR_SRC);
	} else if ( isNotNullEmpty(elemBefore) && elemBefore.prev().attr("type") != "errorStar" && !msgElemExists(elemBefore.prev()) ) {
		if ( isNotNullEmpty(beforeMsg)) {
			message = getMessage(beforeMsg);
			elemBefore.before("<span class='"+classType+"'>"+message+"</span>");
		} else {
			elemBefore.before(ERROR_STAR_IMG);
		}
	}
	
	//Check if there is already an message shown.
	if ( isNotNullEmpty(elemAfter))  {
		message = getMessage(afterMsg);
		var nextElem = getMsgElemNext(elemAfter);
		if ( !msgElemExists(nextElem.next()) ) {
			//Display the error message after the designated elem			
			nextElem.after("<span class='"+classType+"'>"+message+"</span>");
		} else {
			//Update the error message.			
			nextElem.next().html(message);
			nextElem.next().attr("class", classType);
		}
		
	} 
	//set error in heading
	headingErrorMsg = "Incorrect / Incomplete Information";
	
	$("div[name='"+section+"']").children().children(".errorHeadingTxt").html(headingErrorMsg);	
}



/*
* Clear the error for this elem
*
* @param	elemBefore	The element that is after the errorStar .
* @param	elemAfter 	the element that is before error message.
*/
function clearMsg(elemBefore, elemAfter) {
	//console.log("clearing");
	if (isNotNullEmpty(elemBefore) ) {
		//Check if there is already an error star
		if ( elemBefore.attr("class") == "requiredStar") {
			//Change the error star back to the required  star
			elemBefore.prev().remove();
			elemBefore.before(REQUIRED_STAR_IMG);
		} else if ( elemBefore.prev().attr("type") == "errorStar") {
			elemBefore.prev().remove();
		}
		
		//Check if there is already an error message shown.
		if ( msgElemExists(elemBefore.prev()) ) {
			elemBefore.prev().remove();
		}
	}//if (isNotNullEmpty(elemBefore) ) {
	
	var nextElem = getMsgElemNext(elemAfter);
	//Check if there is already an error message shown.
	if ( isNotNullEmpty(nextElem) &&  msgElemExists(nextElem.next()) ) {
		nextElem.next().remove();
	}
	
	
	
}

/*
* Determine which element after the input text is the correct mesage elem to update
*/
function getMsgElemNext(curElem) {
	if ( isNotNullEmpty(curElem) && ( curElem.next().hasClass(EBAY_FEE_ICON) || curElem.next().hasClass("charleft") ) )  {
		return curElem.next();
	} else {
		return curElem;
	}	
}

/*
* Determine if the errror or good msg elem already exists.
*/
function msgElemExists(curElem) {
	if ( curElem.attr("class") == ERROR_TEXT || curElem.attr("class") == GOOD_TEXT ) {
		return true;
	}
	
	return false;
}

/*
* If user presses the enter key in the text box, this will execute on onclick event to the designated element
* to simulate a submit.
*
* @param event		the key event
* @param elem		the elem to recieve the click event.
*/
function enterKeyPressed(e, elem){
	var returnKey = "13";
	var key;

	if(window.event) {
		key = window.event.keyCode;     //IE
	} else {
		key = e.which;     //firefox
	}
	
	if (key == returnKey) {
		//hit the search button.
		$(elem).click();
		return false;
	}
	
	

}


/***************************************************
Validate DAte
****************************************************/
/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//The date format should be : mm/dd/yyyy
		return "InvalidFormat";
	}
	if (strMonth.length<1 || month<1 || month>12){
		//Please enter a valid month
		return "InvalidMonth";
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//Please enter a valid day
		return "InvalidDay";
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//Please enter a valid 4 digit year between "+minYear+" and "+maxYear
		return "InvalidYear";
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//Please enter a valid date
		return "InvalidDate";
	}
	
	return "";
}

function getPacificTime() {
	
	offset = -8; //Paciific time offset
	
    // create Date object for current location
    d = new Date()
   
    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);
   
    // create new Date object for different city
    // using supplied offset
    nd = new Date(utc + (3600000*offset));

    return  nd;

}

/*
* Uses the jquery.textareaCounter.js plugin to create the counter.
*
* @param elem	The text area elem
* @param limit	The max number of characters.
*/
function runTextAreaCounter(elem, limit, nodeType) {
	if ( isNullEmpty (nodeType) ) {
		nodeType = "div";				  
	}
	var counterSettings = {
		'initialDisplay': true,
		'nodeType': nodeType,
		'maxCharacterSize': limit,
		'displayFormat': '#left characters remaining'
	};
	$(elem).textareaCount(counterSettings);
	
}

/********************************
* Gigya Wildfire Application
*********************************/
function changeEmbedSize(elem, itemId) {
	var size = elem.value;
	var width;
	var height;
	if (size == "thumb") {
		width = null;
		height = null;
	} else if (size == "small") {
		width = 400;
		height = 600;
	} else if (size == "medium") {
		width = 600;
		height = 900;
	} else {
		width = 800
		height = 1200
	} 
	
	var code = $("#theCode").html();
	//Will only change the width and height if those has been set. 
	//Otherwise it will use the normal size.
	var title = $("#thumbImage").attr("title");
	var thumbSrc = $("#thumbImage").attr("src");
	if (isNotNullEmpty(width)) {
		//Replace the size.
		code = code.replace(/width=\".{3,4}\"/g, 'width="'+width+'"');
		code = code.replace(/height=\".{3,4}\"/g, 'height="'+height+'"');
		//Add the "Buy it on eBay" button
		code = code.replace(/docId=/g, "buy=true&docId=");
	} else {		
		var domain = $("#serverInfo").attr("domain");
		var thumbUrl = "http://"+domain+"/showcase.jsp?item="+itemId;
		code = '&lt;a href="'+thumbUrl+'"&gt;&lt;img src="'+thumbSrc+'" width="200" height="300"&gt;&lt;/a&gt;';
	}
	$("#codeArea").html(code);
	updateWildfire(title, thumbSrc);
}

function updateWildfire(title, thubSrc) {
	var pconf={
	   useFacebookMystuff: 'false',
	   defaultPreviewURL: thubSrc,
	  	facebookPreviewURL: thubSrc,
	   facebookPreviewURL2: thubSrc,
	   facebookPreviewURL3: thubSrc,
	  widgetTitle: "View Full Size", 
	  widgetDescription: title,
	  contentIsLayout: 'false', 
	  defaultContent: 'codeArea', 
	  showCodeBox: "true",
	  UIConfig: '<config baseTheme="v2"><display showEmail="true" showBookmark="false" showCloseButton="false" networksToShow="facebook, blogger, livespaces, livejournal, myyearbook, vox, xanga, multiply, igoogle, netvibes, pageflakes, yahoo, eons, overblog"></display><body><controls><snbuttons iconsOnly="false"></snbuttons></controls></body></config>'
	};
	Wildfire.initPost('817571', 'divWildfirePost', 450, 300, pconf);
}

/*
* Use to highlight the knowledge center left navigation.
*
* @param	selection	li element to highlight.
*/
function kcHighlightSelection(selection) {
	$(selection).parent().siblings().each(function() {
		$(this).css("backgroundColor","");										  
	});
	 $(selection).parent().css("backgroundColor","#c2d5e5");
}



//Start the chat box
//Requires the chat script to be on the page
function startChat() {	
	$("#l2s_trk img").click();     //IE
	$("#l2s_trk a").click();    //firefox
	
}

/*
* Retrive the store categories from ebay.
*/

function syncStoreCategories() {
	//Hide the store category options
	displayStoreCategoryOptions(false);
	$.ajax({
	   type: "POST",
	   url: "/builder/listing?op=getStore",
	   data: "load=true",
	   success: function(data, textStatus){ 
	   		if ( isNotNullEmpty(data.store) && isNotNullEmpty(data.store.categories)) {
				$(EBAY_STORE_CAT_1).html(  createStoreCatOptions(data.store.categories, 1) );
				$(EBAY_STORE_CAT_2).html(  createStoreCatOptions(data.store.categories, 2) );
				$(EBAY_STORE_CATS_RELOAD).html('<a href="#" stoplink=1 id="syncStoreCats" onclick="syncStoreCategories()">Click here</a> to update your eBay store categories.');
				$(EBAY_STORE_CATS_AREA).show();
				displayFadeMsg($(EBAY_STORE_CATS_RELOAD), "StoreCategoryUpdated", "good");
				
				if ($(LISTING_TYPE+":checked").val() != "FixedPriceItem") {
					setInitialListingType();
				};
				
			} else {
				//User doesnt' have store				
				$(EBAY_STORE_CATS_RELOAD).html('<span class="errorMsgs">You do not have a eBay Store.</span>');
			}
			displayStoreCategoryOptions(true);
		},
		error :  function (XMLHttpRequest, textStatus, errorThrown) {
			$(EBAY_STORE_CATS_RELOAD).html('<span class="errorMsgs">We were not able to update your eBay Store categories</span> <br><a href="#" stoplink=1 onclick="syncStoreCategories()">Click here</a> to try again.');
			displayStoreCategoryOptions(true);
		},
	   dataType : "json"
	 });
}

/*
* Sync the user's listing information with ebay.
*/
function syncToEbay() {
	$.ajax({
		type: "POST",
		url: "/ajaxCalls/syncToEbay.jsp",
		dataType : "html"
	 });	
};	








/***************************************************************************
GLOBAL - This is the start of the global class I'm trying to redo.
****************************************************************************/

var LIB = new Object();
/*
* GLOBAL Class
*/

/*
Strictly check a list of variables types agains a list of arguments
@param	types	a array of variables types 
				[Object,Array,Function,String,Number,Boolean,Constructor]
@param 	args	a array of aguments.
*/
LIB.strictArg = function (types, args) {
	//Make sure the number of types and args matches
	if (types.length != args.length) {
		throw "Invalid number of arguments. Expected " + types.length + ", recieved " + args.length + " instead.";	
	}
	
	for (var i=0; i < args.length; i++) {
		if (args[i].constructor != types[i] ) {
			throw "Invalid argument type. Expected " + types[i].name + ", recieved " + args[i].constructor.name + " instead.";	
		}
	}
}

/*
* Given a did (that belongs to user=1), this will transfer that page design
* to the user's account that is signed in.
*
* @param did	The demo document id after user has saved it.
*
* return true|false of whether the page disgn was saved successfully.
*/
LIB.saveDemoToDraft = function(did) {
	this.strictArg([String], arguments);
	$.ajax({
	   type: "post",
	   url: "/builder/listing",
	   data: "op=changeOwner&did="+did,
	   dataType: "text",
	   success: function(data){ 				
			return true;
		},
		error :  function (XMLHttpRequest, textStatus, errorThrown) {
			return false;
		}
	 });

}

/*
* Given a did (that belongs to user=1), this will transfer that page design
* to the user's account that is signed in.
*
* @param url	The getUrl of the page content to grab	
* @param elem	The element to put the content into
*
* return true|false of whether the page disgn was saved successfully.
*/
LIB.getSetHtmlContent = function(getUrl, elem) {
	this.strictArg([String, String], arguments);
	$.ajax({
	   type: "post",
	   url: getUrl,
	   dataType: "html",
	   success: function(data){ 				
			$(elem).html(data);
		},
		error :  function (XMLHttpRequest, textStatus, errorThrown) {
			
		}
	 });

}








