function getObj(name) {
	if (document.getElementById) {
		return document.getElementById(name);
	}
	else if (document.all) {
		return document.all[name];
	}
	else if (document.layers) {
		return document.layers[name];
	}
}

function updateCart(jsIVID){
	$.get('/webservice/reloadCart', function(data){
		eval(data);
		
		var oldHTML = $('#numItems').html();
		var newHTML = oldHTML.substring(0, oldHTML.indexOf('cart:') + 9);
		
		newHTML = newHTML + jsCartInfo.numcartitems;
		if(jsCartInfo.numcartitems == 1)
			newHTML = newHTML + ' item ' + jsCartInfo.cartsubtotal;
		else
			newHTML = newHTML + ' items ' + jsCartInfo.cartsubtotal;
			
		newHTML = newHTML + oldHTML.substring(oldHTML.length - 4);
		$('#numItems').html(newHTML);
	});
	
	$('a[id^=delete_' + jsIVID + ']').remove();
	$('input[id^=count_' + jsIVID + ']').remove();
	$.get('/webservice/getInCart?IVID=' + jsIVID, function(data){
		eval(data);
		
		for(i in jsInCartStruct){
			$('<input type="hidden" id="count_' + jsIVID + '_' + i + '_' + 1 + '">').insertBefore('#ItemQtyIV_' + jsIVID);
		}
	});
	setTimeout(function() {showDelLink(jsIVID)}, 500);
	//$('#addcartmsg_' + jsIVID).fadeOut(4000);
}

function showDelLink(thisIVID){
	var IVIDHasItemID = new Array();
	
	$('form[id^=changeQty_]').each(function(index, item){
		IVIDHasItemID[this.id.substring(10)] = 0;
	});
	
	$('input[id^=count_' + thisIVID + ']').each(function(index, item){
		var id = this.id;
		var thisIVID_full = id.substring(id.indexOf("_") + 1);
		var thisID = thisIVID_full.substring(thisIVID_full.indexOf("_") + 1);
		var thisCount = thisID.substring(thisID.indexOf("_") + 1);
		
		thisID = thisID.substring(0, thisID.lastIndexOf(thisCount) - 1);
		
			if(IVIDHasItemID[thisIVID] == 0){
				$('<a id="delete_' + thisIVID + '" href="/post/addtocart"><img title="Remove all copies from cart" src="/res/images_icons/removefromcart.gif"></a>').insertAfter('#changeQty_' + thisIVID);
				$('#delete_' + thisIVID).click(function(){
					$.get('/webservice/getInCart?IVID=' + thisIVID, function(data){
						eval(data);
						$('#ItemQtyIV_' + thisIVID).val(0);
						
						for(i in jsInCartStruct){
							window.location.href = '/post/addtocart?ItemID=' + i + '&Qty=' + 0;
							$('input[id^=count_' + thisIVID + '_' + i + ']').remove();
						}
						$('#addcartmsg_' + thisIVID).html('All copies removed from <a href="/cart">cart</a>.');
						$('#addcartmsg_' + thisIVID).show();
						setTimeout(function() {updateCart(thisIVID)}, 500);
					});
					return false;
				});
				IVIDHasItemID[thisIVID] = 1;
			}
	});
}

function updateCart_ItemListings(jsItemID){
	$.get('/webservice/reloadCart', function(data){
		eval(data);
		
		var oldHTML = $('#numItems').html();
		var newHTML = oldHTML.substring(0, oldHTML.indexOf('cart:') + 9);
		
		newHTML = newHTML + jsCartInfo.numcartitems;
		if(jsCartInfo.numcartitems == 1)
			newHTML = newHTML + ' item ' + jsCartInfo.cartsubtotal;
		else
			newHTML = newHTML + ' items ' + jsCartInfo.cartsubtotal;
			
		newHTML = newHTML + oldHTML.substring(oldHTML.length - 4);
		$('#numItems').html(newHTML);
	});
}

/* should be in shared resources folder, but I can't reach it from the tree */

/************************
*
*	Windowed popups.
*
************************/

var newwindow;
var wheight = 0, wwidth = 0;

function popitup5(url, title, iwidth, iheight, colour) {
	var pwidth, pheight;
	if ( !newwindow || newwindow.closed ) {
		pwidth=iwidth+30;
		pheight=iheight+30;
		newwindow=window.open('','htmlname','width=' + pwidth +',height=' +pheight + ',resizable=1,top=50,left=10');
		wheight=iheight;
		wwidth=iwidth;
		}

	if (wheight!=iheight || wwidth!=iwidth ) {
		pwidth=iwidth+30;
		pheight=iheight+90;
		newwindow.resizeTo(pwidth, pheight);
		wheight=iheight;
		wwidth=iwidth;
		}

	newwindow.document.clear();
	newwindow.focus();
	newwindow.document.writeln('<html> <head> <title>' + title + '<\/title> <\/head> <body bgcolor= \"' + colour + '\"> <center>');
	newwindow.document.writeln('<img src=' + url + ' title=\"' + title + '\" alt=\"' + title + '\" >');
	newwindow.document.writeln('<\/center> <\/body> <\/html>');
	newwindow.document.close();
	newwindow.focus();
	}

	// Routines to tidy up popup windows when page is left
	// Call with an onUnload="tidy5()" in body tag

function tidy5() {
	if (newwindow && !newwindow.closed) { newwindow.close(); }
	}

/************************
*
*	Explanatory popups.
*
************************/

function ShowTextPopup(hoveritem) {
	hp = document.getElementById("hoverpopup");

	// Set position of hover-over popup
	hp.style.top = hoveritem.offsetTop + 18;
	hp.style.left = hoveritem.offsetLeft + 20;

	// Set popup to visible
	hp.style.visibility = "Visible";
	}

function HideTextPopup() {
	hp = document.getElementById("hoverpopup");
	hp.style.visibility = "Hidden";
	}

/************************
*
*	Input validation.
*
************************/
var AlreadyClicked = false;
function RunClickOnce(){
	if (AlreadyClicked) {
		alert("You have already submitted your order. Please wait as your order is processed. If after a minute or two your order still appears not to have been processed, please email customerservice@mycomicshop.com and we will confirm whether or not your order has been received.");
		return false;
	}
	else {
		AlreadyClicked = true;
		return true;
	}
}

function changeImg(ItemID, DisplaySequence, Caption, ImgPathMed, ImgPathLarge) {
	b = '';
	b += '<a href="/res/catimg_v/' + ImgPathLarge + '">';
	if (Caption.length > 0) {
		b += Caption + '<br>';
	}
	b += '<img src="/res/catimg_v/' + ImgPathMed + '" border=0 width=300></a>';
	getObj('MedImg_'+ItemID).innerHTML = b;
}

var cartObj = "";
var cartMsg = "";
var wlObj = "";
// for items on item detail page
function addItemToCart(ItemID) {
	cartObj = getObj('cartMsgHolder_' + ItemID);
	cartObj.style.visibility = "hidden";
	setTimeout(setAddItemToCartCartMsg, 200);
	return true;
}
function setAddItemToCartCartMsg() {
	cartObj.innerHTML = 'Added to your <a href="/cart">cart</a>';
	cartObj.style.visibility = "visible";
}


// for items added to cart from issue listings
function addToCart(IVID, MaxOrderQty) {
	cartObj = getObj('addcartmsg_' + IVID);
	var qty = getObj('ItemQtyIV_' + IVID).value;
				
	if (MaxOrderQty == 'X') {
		theSel = getObj('ItemSelIV_' + IVID);
		MaxOrderQty = theSel.options[theSel.selectedIndex].value.split('_')[1];
	}
	
	if (qty <= MaxOrderQty) {
		if (qty == 0) {
			cartMsg = 'All copies removed from <a href="/cart">cart</a>.';
		}
		else if (qty == 1) {
			cartMsg = '1 was put in your <a href="/cart">cart</a>.';
		}
		else {
			cartMsg = '' + qty + ' were put in your <a href="/cart">cart</a>.';
		}
	}
	else {
		if (MaxOrderQty == 1) {
			cartMsg = 'Only 1 copy is available. It has been added to your <a href="/cart">cart</a>.';
		}
		else {
			cartMsg = 'Only ' + MaxOrderQty + ' copies are available. ' + MaxOrderQty + ' have been put in your <a href="/cart">cart</a>.';
		}
	}
	cartObj.style.visibility = "hidden";
	setTimeout(function() {setAddToCartMsg(IVID)}, 200);
	return true;
}
function setAddToCartMsg(IVID) {
	cartObj.innerHTML = cartMsg;
	cartObj.style.visibility = "visible";
	setTimeout(function() {updateCart(IVID)}, 1000);
}


// for items added to cart from item listings
function addToCart_ItemListings(ItemID, MaxOrderQty) {
	cartObj = getObj('addcartmsg_' + ItemID);
	var qty = getObj('ItemQty_' + ItemID).value;
				
	if (qty <= MaxOrderQty) {
		if (qty == 0) {
			cartMsg = 'All copies removed from <a href="/cart">cart</a>.';
		}
		else if (qty == 1) {
			cartMsg = '1 was put in your <a href="/cart">cart</a>.';
		}
		else {
			cartMsg = '' + qty + ' were put in your <a href="/cart">cart</a>.';
		}
	}
	else {
		if (MaxOrderQty == 1) {
			cartMsg = 'Only 1 copy is available. It has been added to your <a href="/cart">cart</a>.';
		}
		else {
			cartMsg = 'Only ' + MaxOrderQty + ' copies are available. ' + MaxOrderQty + ' have been put in your <a href="/cart">cart</a>.';
		}
	}
	cartObj.style.visibility = "hidden";
	setTimeout(function() {setAddToCartMsg_ItemListings(ItemID)}, 200);
	return true;
}
function setAddToCartMsg_ItemListings(ItemID) {
	cartObj.innerHTML = cartMsg;
	cartObj.style.visibility = "visible";
	setTimeout(function() {updateCart_ItemListings(ItemID)}, 1000);
}


function addToWL(IVID, IsLoggedIn) {
	wlObj = getObj('WLMsg_' + IVID);
	wlObj.style.visibility = "hidden";
	if (IsLoggedIn) {
		setTimeout(setWLMsg, 200);
		return true;
	}
	else {
		setTimeout(setWLFailedMsg, 200);
		return false;
	}
}
function changeWLGrade(IVID) {
	wlObj = getObj('WLMsg_' + IVID);
	wlObj.style.visibility = "hidden";
	setTimeout(setWLGradeChangedMsg, 200);
	return true;
}
function setWLMsg() {
	wlObj.innerHTML = '<br>Added to your <a href="/wantlist">want list</a>.';
	wlObj.style.visibility = "visible";
}
function setWLGradeChangedMsg() {
	wlObj.innerHTML = '<br>Grade preference updated.';
	wlObj.style.visibility = "visible";
}
function setWLFailedMsg() {
	wlObj.innerHTML = '<br>You must be <a href="/login">logged in</a> to add items to your <a href="/wantlist">want list</a>.';
	wlObj.style.visibility = "visible";
}

function showpreviewsiteminfo(SubItemID) {
	myWindow = window.open("/subscriptionservice/viewitem?addbutton=No&SubItemID=" + SubItemID, "ItemInfo", "width=520,height=400,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1");
}

function checkEmail2() {
	var email = getObj('emailaddress');
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email.value)) {
		alert('The email address "'+email.value+'" does not appear to be valid.\n Please try again.');
		email.focus;
		return false;
	}
}

function querySeperator(URLfrag) {
	if (URLfrag.indexOf('?') == -1) return '?';
	return '&';
}

function changeTitlesPerPage(baseURL) {
    var myindex  = getObj('SetTitlesPerPage').selectedIndex;
    var SelValue = getObj('SetTitlesPerPage').options[myindex].value;
    var theURL  = baseURL + querySeperator(baseURL) + 'SetTitlesPerPage=' + SelValue;
    top.location.href = theURL;
    return true;
}
function changeIssuesPerPage(baseURL) {
    var myindex  = getObj('SetIssuesPerPage').selectedIndex;
    var SelValue = getObj('SetIssuesPerPage').options[myindex].value;
    var theURL  = baseURL + querySeperator(baseURL) + 'SetIssuesPerPage=' + SelValue;
    top.location.href = theURL;
    return true;
}