var dropdownvisible = false;

function pageCommonInit()
{
	var e;

	redirectToWWWifNeeded();

	$("a.captionlink").attr("onmouseover", "this.style.textDecoration='underline';"); 	
	$("a.captionlink").attr("onmouseout", "this.style.textDecoration='none';");
	
	BuildRecentlyViewed();
	BagDisplaySummary();

	if(ge('narrowfooter'))
	{
		girlpropsPositionFooter();
	}
	
 	e = ge("searchstring");

	var n;
	
	// tweak the positioning on the search box
	if(e !== null && Gecko && ! Safari)
	{
		n = parseInt(e.style.top, 10);
		e.style.top = "2px";
		e.style.height = "58%";
	
		n = parseInt(e.style.width, 10);
		e.style.width = (n - (Camino ? 6 : 3)) + "px";
	}

	if(e !== null && InternetExploder && Windoze)
	{
		n = parseInt(e.style.width, 10);
		e.style.width = (n - 5) + "px";
	}

	if(e !== null && InternetExploderSeven)
	{
		n = parseInt(e.style.top, 10);
		e.style.height = "14px";
	}
	
	if(e !=- null && (SafariThree || SafariFour))
	{
		n = parseInt(e.style.top, 10);
		e.style.top = (n - 1) + "px";
		e.style.height = "15px";
	
		n = parseInt(e.style.width, 10);
		e.style.width = (n - 4) + "px";
	}
	
	if(InternetExploder && Macintosh)
	{
		document.body.style.backgroundColor = '#32D4CB';
	}
	
	if(e)
	{
		e.style.display = 'block';
	}
	
	e = ge("bottom");
	if(Safari)
	{
		e.style.height = "26px";
	}
		
	DeleteCookieInDomain('girlprops.com', 'propagandafrom');
	DeleteCookieInDomain('girlprops.com', 'search');
	DeleteCookieInDomain('girlprops.com', 'navbar');
	DeleteCookieInDomain('girlprops.com', 'caturi');
	DeleteCookieInDomain('girlprops.com', 'itemtracker');
	DeleteCookieInDomain('girlprops.com', 'sesame');
	DeleteCookieInDomain('girlprops.com', 'recentlyviewed');
	DeleteCookieInDomain('girlprops.com', 'pageof');

	if(InternetExploderFive || InternetExploderSix)
	{
		$("a").focus(function() { this.blur(); });
	}
		
	hardenButtons();
	fixCaptions();
	
	if(pagenamesqz !== "")
	{
		$("#menu" + pagenamesqz).attr("class", "menuitemhl");
	}
	
	$("div.menuitem").mouseenter(function() { $("#" + this.id).attr("class", "menuitemover"); });
	$("div.menuitem").mouseleave(function() { $("#" + this.id).attr("class", "menuitem"); });

	$("#toolbarcappng").each(function(i) { el_fnFixPng(this); });
	$("#bottompng").each(function(i) { el_fnFixPng(this); });
	$("#bottomnavpng").each(function(i) { el_fnFixPng(this); });
	
	var req = new Object;
	req.success = bagQuerySuccess;
	AjaxQueryShoppingBag(req);
}

function bagQuerySuccess(bagData, statusText)
{
	bag = bagData;
	bagBusy = false;
	if(bag.count > 0)
	{
		SetCookie("itemtracker", $.toJSON(bag.itemtracker));
	}
	else
	{
		SetCookie("itemtracker", "");
	}
		
	BagDisplaySummary();
}

function redirectToWWWifNeeded()
{
	var delim = '/RetailScience/';
	if(document.location.href.indexOf('RetailScience') == -1)
	{
		delim = '/r/';
	}
	
	var uriparts = document.location.href.split(delim);
	var uripath;
	var properhost = 'http://' + thishost;

	if(uriparts.length === 1)
	{
		properhost = 'http://' + thishost + "/" ;
		var properhost1 = 'http://' + thishost;
		if(uriparts[0] !== properhost && uriparts[0] !== properhost1)
		{
			document.location.href = properhost;
		}
		
		return;
	}

	uripath = uriparts[1].split('/');
	
	if(uripath[0] === 'page1' || uripath[0] === 'page2' || uripath[0] === 'd' || uripath[0] === '/')
	{
		if(uriparts[0] !== properhost)
		{
			document.location.href = properhost + delim + uriparts[1];
		}
	}
}


function fixCaptions()
{
	$(".captionlink").mouseenter(function() { this.style.textDecoration = 'underline'; } );
	$(".captionlink").mouseleave(function() { this.style.textDecoration = 'none'; } );
}

function pageInitNavbar()
{
	var e = ge("pagechooser");
	if(! e)
	{
		return;
	}
	
	var i;
	var html = "";
	
	if(pagetype == 'page1')
	{
		if(ajax)
		{
			$("#pageof").html(unescape(pagename));
			$("#prevarrow").attr("href", prevmajorpageuri);
			$("#nextarrow").attr("href", nextmajorpageuri);
			$("#prevbutton").attr("href", prevmajorpageuri);
			$("#nextbutton").attr("href", nextmajorpageuri);
		}
		else
		{
			html += '<span>View Page&nbsp;';
			for(i = 1; i <= maxpagenumber; i++)
			{
				html += '<a class="nlnk" ';
				if(i == pagenumber)
				{
					html += 'style="color: #ff1cac;" ';
				}
				
				html += 'href="' + baseuri + '/' + i + '">' + i + '&nbsp;</a>';
			}
		
			html += '<a class="nlnk" href="' + baseuri + '/all">All</a>';
			html += '</span>';
			e.innerHTML = html;
	
			html = "";
			if(pagenumber != -1)
			{
				html = 'Page ' +  pagenumber + ' of ' +  maxpagenumber;
			}
			else
			{
				html = 'All Items';
			}
			
			ge("pageof").innerHTML = html;
			ge("pagetitle").innerHTML = unescape(pagename);
		}
	}
	
	if(pagetype == 'page2' || pagetype == 'checkout' || pagetype == 'propaganda')
	{
		ge("pageof").innerHTML = unescape(pagename);
	}
}

var cbendless;
var epfirst = true;
var eop = false;
var eopmargin;
var eopobjorder;
var docheight;
var resizelock;

function pageInitEndlesspage(cbfunc, margin)
{
	if(! ajax)
	{
		return;
	}
	
	cbendless = cbfunc;
	eopmargin = margin;
	docheight = $(document).height();
	resizelock = false;

	cbendless();
	
//	if($(window).height() >= $(document).height())
//	{
//		cbendless();
//	}
//	else
//	{
//		if($(window).scrollTop() >= $(document).height() - $(window).height())
//		{
//			cbendless();
//		}
//	}
	
	$(window).scroll(
		function()
		{
			if($(window).scrollTop() > $(document).height() - $(window).height() - eopmargin)
			{
				cbendless();
			}
		}
	);

	$(window).resize(
		function()
		{
			if($(window).height() > docheight && ! resizelock)
			{
				resizelock = true;
				cbendless();
			}
		}
	);
}

function endlessPage1()
{
	if(eop)
	{
		return;
	}
	
	var objorder = $(".p1div:last").attr("id").substr(6);
	if(objorder == eopobjorder)
	{
		return;
	}
	
	eopobjorder = objorder;
	$("#endlessloader").css({ 'display' : 'inline-block' });
	window.setTimeout("endlesspage1Part2()", 50);
}

function endlesspage1Part2()
{
	var objorder = $(".p1div:last").attr("id").substr(6);
	$.get("/RetailScience/endlesspage1/" + pagenamesqz + "/" + objorder,
		function(data)
		{
			if(data !== "")
			{
				$(".p1div:last").after(data);
				if(customerType == 2 || customerType == 4)
					BagGenerateWholesalePrices();
				var n = docheight;
				docheight = $(document).height();
			}
			else
			{
				eop = true;
			}
			resizelock = false;

			$("#endlessloader").css({ 'display' : 'none' });
		}
	);

	if($(window).height() >= $(document).height() && siteid == 'fl' && epfirst)
	{
		window.setTimeout("endlessPage1()", 250);
	}
		
	epfirst = false;
}

function BuildRecentlyViewed()
{
	var p;
	var i;
	var html = "";
	
	return;
	
	var history = locationList('recentlyviewed');
	var recentitems = ge('recentitems');
	if(history.length < 1)
	{
		return;
	}
		
	for(i = 0; i < history.length; i++)
	{
		var h = history[i];
		var uri = h.getProperty('uri');
		var uriparts = uri.split('/');
		var objtable = uriparts[uriparts.length - 2];
		var objid = uriparts[uriparts.length - 1];

		html += '<div class="recent"';
		if(i === 0)
		{
			html += ' style="margin-top: 0px"';
		}
		
		html += '>';
	
		html += '<table cellpadding="0">';
		html += '<tr>';
		html += '<td><a class="imglink" href="';
		html += uri;
		html += '"><img class="photo" style="width: 40px; height: 40px; border: 1px solid #FF1CAC;" onmouseover="this.style.borderColor=\'#000\';" onmouseout="this.style.borderColor=\'#FF1CAC\';" src="/RetailScience/thumbfor/';
		html += objtable + '/' + objid + '" alt="" /></a></td>';
		html += '<td class="recenttext"><a class="recentlink" href="' + uri + '" onmouseover="this.style.textDecoration=\'underline\';" onmouseout="this.style.textDecoration=\'none\';">' + Prune(h.getProperty('title'), 40) + '</a></td></tr>';
		html += '</table></div>';
	}
	
	
	p = ge('recentlyviewed');
	if(p)
	{
		p.style.visibility = 'visible';
		p.style.height = 92 + ((history.length - 1) * 50) + "px";
		if(InternetExploder)
		{
			p.style.height = 75 + ((history.length - 1) * 50) + "px";
		}
	}

	p = ge('recentitems');
	if(p)
	{ 
		p.style.visibility = 'visible';
		p.style.height = 45 + ((history.length - 1) * 50) + "px";
		if(InternetExploder)
		{
			p.style.height = 48 + ((history.length - 1) * 50) + "px";
		}
	}

	recentitems.innerHTML = html;
}

function searchEnter()
{
	var search = ge("searchstring").value;
	if(search == 'Search' || search === '')
	{
		modalMessage('Search Engine', '<p class="body" style="margin-top: 15px;">Please enter a search string, then click &ldquo;GO&rdquo</p>', 500);
		return(false);
	}
	search = escape(search);
	var href='http://' + thishost + '/RetailScience/search?searchstring=' + search;
	document.location.href = href;

	return(false);
}

function search()
{
	var search = ge("searchstring").value;
	if(search == 'Search')
	{
		modalMessage('Search Engine', '<p class="body" style="margin-top: 15px;">Please enter a search string, then click &ldquo;GO&rdquo</p>', 500);
		return;
	}
	search = escape(search);
	var href='http://' + thishost + '/RetailScience/search?searchstring=' + search;
	document.location.href = href;
}

function BuildNavBar(levels)
{
	var html = "";
	
	var count = 0;
	var history = selectedLocationList('navbar', levels);
	var width = new Array;
	var needspruning = new Array;
	var hasposition0 = false;
	var p;
	
	for(i = 0; i < history.length; i++)
	{
		p = history[i];
		if(p.getProperty('position') === 0)
		{
			hasposition0 = true;
		}
			
		width[i] = TextWidth(p.getProperty('title'));
		needspruning[i] = false;
		count += width[i];
	}
	
	if(count > hasposition0 ? 70 : 90)
	{
		var nitems = 1;
		var delta = count - (hasposition0 ? 65 : 85);
		if(delta > 25)
		{
			delta /= 2;
			nitems = 2;
		}
		
		for(i = width.length - nitems; i < width.length; i++)
		{
			needspruning[i] = true;
			width[i] -= delta;
		}
	}

	var hasdropdown = false;
	for(i = 0; i < history.length; i++)
	{
		p = history[i];
		if(html.length > 0)
		{
			html += '&nbsp;';
		}
			
		html += '&gt;&nbsp;';
		if(i != history.length - 1)
		{
			html += '<a class="nav" onmouseover="this.style.textDecoration=\'underline\';" onmouseout="this.style.textDecoration=\'none\';" href="';
			html += p.getProperty('uri');
			html += '">';
		}
	
		var snip = needspruning[i] ? Prune(p.getProperty('title'), width[i]) : p.getProperty('title');
		html += snip;

		if(i === 0)
		{
			html += " (" + GetCookie('pageof') + ")";
		}
		
		if(i != history.length - 1)
		{
			html += '</a>';
		}

//		if(p.getProperty('position') == 0)
//		{
//			hasdropdown = true;
//			html += '&nbsp;&nbsp;<img class="photo" style="width: 90px;" src="/images/dropdownspacer.gif" id="dropdownspacer" />&nbsp;';
//		}
	}
	
	p = ge("navfrompage");
	if(p)
	{
		p.innerHTML = html;
	}
	
//	if(hasdropdown)
//		BuildDropdown();
}

function girlpropsGo(pageid)
{
	var uri = page2uri + pageid;
	
	window.location.href = uri;
}

function girlpropsPrintable(orderid)
{
	var uri = "/RetailScience/receipt?orderid=" + orderid;

	winx = 100; winy = 100;
	if(window.screenX) winx = window.screenX + 25;
	if(window.screenLeft) winx = window.screenLeft + 25;
	if(window.screenY) winy = window.screenY + 40;
	if(window.screenTop) winy = window.screenTop + 25;
	var opt = "menubar,scrollbars,resizable,width=680,height=480,top=" + winy + ",left=" + winx;
	var win = window.open(uri, "viewer", opt);
	win.moveTo(winx, winy);
	win.focus();
}

function girlpropsPositionFooter()
{
	if(ge('markercontent'))
	{
		var height = findTopCoord(ge('markercontent'));
		var footer;
		footer = ge('narrowfooter');
		footer.style.top = height + 'px';
		footer.style.visibility = 'visible';
	}
}

function absoluteTop(e)
{
	var top = e.offsetTop;
	var p = e.parentNode;
	while(p)
	{
		top += p.offsetTop;
		p = p.parentNode;
	}
	
	return(top);
}

function focusAndSelect(formname,elemname)
{
	var el = document.forms[formname].elements[elemname];
	el.focus();
	if(el.tagName != 'SELECT')
		el.select();
}

function focusNext(el, elemName, evt)
{
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode :
				   ((evt.which) ? evt.which : evt.keyCode);
    if(charCode == 13)
	{
		var str = 'focusAndSelect("' + el.form.name + '", "' +   elemName + '")';
		window.setTimeout(str, 1);
		return false;
    }

	return true;
}

function submitViaEnter(evt)
{
    evt = (evt) ? evt : event;
    var target = (evt.target) ? evt.target : evt.srcElement;
    var form = target.form;
    var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);
   	if(charCode == 13)
	{
		form.submit();
		return false;
	}
    return true;
}

function executeViaEnter(evt, jscode)
{
    evt = (evt) ? evt : event;
    var target = (evt.target) ? evt.target : evt.srcElement;
    var form = target.form;
    var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);
   	if(charCode == 13)
	{
		eval(jscode);
		return false;
	}
    return true;
}

function getElementStyle(elemID, IEStyleProp, CSSStyleProp) {
    var elem = document.getElementById(elemID);
    if (elem.currentStyle) {
        return elem.currentStyle[IEStyleProp];
    } else if (window.getComputedStyle) {
        var compStyle = window.getComputedStyle(elem, null);
		var s = compStyle.getPropertyValue(CSSStyleProp);
        return s;
    }
    return "";
}

function pngifyTable(table)
{
	if(InternetExploderSix || InternetExploderSeven)
	{
		var fixed = 0;
		$("img.rctl", table).each(function() { fixed = 1 });
		if(fixed)
		{
			$("td.rctl", table).html('');
			$("td.rctr", table).html('');
			$("td.rcbl", table).html('');
			$("td.rcbr", table).html('');
		}
		
		$("td.rctl", table).append('<img class="rctl" style="width: 16px; height: 32px;" src="/images/cspinktl.png" />');
		$("img.rctl", table).each(function(i) { el_fnFixPng(this); });
		$("td.rctl", table).css('background', 'none');

		$("td.rctr", table).append('<img class="rctr" style="width: 16px; height: 32px;" src="/images/cspinktr.png" />');
		$("img.rctr", table).each(function(i) { el_fnFixPng(this); });
		$("td.rctr", table).css('background', 'none');

		$("td.rcbr", table).append('<img class="rcbr" style="width: 16px; height: 16px;" src="/images/cspinkbr.png" />');
		$("img.rcbr", table).each(function(i) { el_fnFixPng(this); });
		$("td.rcbr", table).css('background', 'none');

		$("td.rcbl", table).append('<img class="rcbl" style="width: 16px; height: 16px;" src="/images/cspinkbl.png" />');
		$("img.rcbl", table).each(function(i) { el_fnFixPng(this); });
		$("td.rcbl", table).css('background', 'none');
	}
}

function hardenButtons()
{
	// this function helps remedy the situation where sometimes the CSS buttons don't "click".
	// it does this by adding an onclick handler to enclosed span, taken from the a element
	if(InternetExploderSix)
	{	
		$("div.button").each(function(i) { hardenButton(this) });
		$("div.smbutton").each(function(i) { hardenButton(this) });
	}
}

function hardenButton(el)
{
	return;
	
	$("a", el).each(
		function(i)
		{
			this.onmouseover = "this.style.color = '#ffe81a'; this.childNodes[0].style.color = '#ffe81a';";
			this.onmouseout = "this.style.color = '#fff'; this.childNodes[0].style.color = '#fff';";
//			$("span", this).each(
//				function(i)
//				{
//					var href = this.parentNode.href;
//					if(href.substr(0, 11).toLowerCase() == 'javascript:')
//						href = href.substr(11);
//					else
//						href = "document.location.href='" + href + "'";
//						
//					this.onclick = href;
//				});
		}); 
}

function continueshopping()
{
	var parts = document.referrer.split('/');
	if(parts[parts.length - 1].substr(0,3) == "bag")
		document.location.href = '/RetailScience/page1';
	else
		history.back();
}

function checkout()
{
	// warning - temp hack job only for fabuless.com using girlprops.com to check out

	var sid = GetCookie("sid");
	if(sid.length == 0)
		document.location.href = "/RetailScience/bag";
		
	document.tempcheckout.sid.value = sid;
	document.tempcheckout.submit();
}

function expressCheckout()
{
	modalHide();
	var html = new Array();
	
	html.push('<table cellpadding="0" cellspacing="0"><tr><td valign="top" style="padding-top:20px;"><img src="/images/PayPal_mark_180x113.gif" style="margin-left: 5px; margin-bottom: 10px;" /><br /><img src="/images/pinkprogressbar.gif" style="width: 191px;"/></td>');
	html.push('<td style="padding-top:20px;" valign="top"><p class="body" style="margin-left: 20px;">We are transferring you to PayPal.  Once there, log in and choose your payment method and shipping address, then click &ldquo;Continue&rdquo; to finish the checkout process.</p></td></tr></table>');
	modalDialog("Checkout using PayPal", html.join(''), 560, "ppexpresscheckout", null);

	window.setTimeout("goExpressCheckout()", 2000);
}

function goExpressCheckout()
{
	document.location.href = 'https://' + thishost + '/RetailScience/expresscheckout?loginpaypal=1';
}

function gpcustomerTypeCallback(resp, statusText)
{
	var req = new Object();
	req.success = bagSuccess;
	AjaxShoppingBag(req);
}	

function go(where)
{
	if(! docReady)
		return;

	switch(where)
	{
		case 'bag':
			if(ajax)
			{
				if(bagActive)
					CloseAjaxShoppingBag();
				else
				{
					if(customerType == -1)
					{
						var req = new Object();
						req.success = gpcustomerTypeCallback;
						req.failure = null;
						AjaxQueryCustomerType(req);
					}
					else
					{
						var req = new Object();
						req.success = bagSuccess;
						AjaxShoppingBag(req);
					}
				}
			}
			else
			{
				document.bag.continueuri.value= thisuri;
				document.bag.submit();
			}
			break;
		
		case 'lostpassword':
			document.location.href = '/RetailScience/lostpassword';
			break;
	}
}


