/**
 * Javascript functions for shop system ver 3 (Shop3)
 */
 


/**
 * Helper function for insertToCart - insert OK
 */
baloons = new Array();
function updateOk(responseText, textStatus, XMLHttpRequest) {
	/**
	 * Extract amount for current item in shopping cart
	 */
	var amount = 1;
	var regEx = new RegExp('value="([0-9]*)"', '') ;
	results = responseText.match(regEx)
	if (results) amount = results[1];

	/**
	 * Update info window / Create a baloon for for hovering on 
	 */
	id = '#boughtbaloon_'+lastclickedel;
	if (jQuery(id).html()==null) {
		// jQuery('#tbl_buybtn'+lastclickedel).append('<div style="positon: absolute; margin-top: -16px; margin-left: 90px;" id="boughtbaloon_'+lastclickedel+'" class="boughtbaloon">Y</div>');
		jQuery('#tbl_buybtn'+lastclickedel).after('<div style="positon: absolute; margin-top: -16px; margin-left: 90px;" id="boughtbaloon_'+lastclickedel+'" class="boughtbaloon">Y</div>');
		// new Insertion.After('tbl_buybtn'+lastclickedel, '<div id="'+id+'" class="boughtbaloon"></div>');
	}
	//	jQuery(id).css({'position': 'absolute', 'margin-top': '-16px', 'margin-left': '90px'});	// THIS CRASHES IE6
	// alert(document.cookie);
	var regEx = new RegExp('value="([0-9]*)"', '') ;
	results = responseText.match(regEx)
	if (results) amount = results[1];

	// lnlang=en
	if (document.cookie.match(/lnlang=en/)) {
		jQuery(id).html('<b>OK, <a href="/?checkout=1">added to cart</a>' + ((amount>1) ? ' ('+amount+')' : '') + '</b>');
	} else {
		jQuery(id).html('<b>OK, lagt i <a href="/?checkout=1">handlekurv</a>' + ((amount>1) ? ' ('+amount+')' : '') + '</b>');
	}
	jQuery(id).show();
	setTimeout(	function () { hideBaloons() }, 5000);
	baloons.push(jQuery(id));
}

function hideBaloons() {
	jQuery.each(baloons, function(){
		this.toggle();
	});
	
}

/**
 * Helper function for insertToCart - insert FAILED
 */
function updateFail() {
	alert('Feil - insert to cart feilet.');
}

/**
 * updateContentFields - updates fields that depends on shoppingcart-updates
 * Like number of items in cart etc
 */
function updateContentFields() {

		/**
		 * Update num items in cart if exists
		 */
		var contnumprods = document.getElementById('shopcartnumproducts');
		if (contnumprods && contnumprods[0].tagName!='') {
			jQuery('#shopcartnumproducts').load("shop3/inserttocart.php?displaynumincart=1");
		}
}

/**
 * Insert a product to shoppingcart
 */
function insertToCart(artid, prodno, amount, flag, altdesc, altprice) {
		lastclickedel = prodno;
		var packel = document.getElementById('prodpack_'+prodno);
		if (packel) {
			// When a product has a minimum amount/packages.
			if (packel.tagName.match(/INPUT/i)==true) {
				amount = packel.options[packel.selectedIndex].value;
			} else {
				amount = packel.value;
			}
		}
		var tmpicParams = "artid: '" + artid + "', prodno: '" + prodno + "', amount: '" + amount + "'"+ ", flag: '" + flag + "'";	// Ajax REQUEST parameters
		var err = false;
		var notfound = '';
		var found = false;
		var foundarr = new Array();
		var foundflagarr = new Array();
		var foundaltprodno = '';
		var custcounter = 0;
		var names = 0;
		var namesselected = 0;
		var prevname = '';
		jQuery('.prodartid'+artid).each(function() {
			custcounter++;
			if (this.type=='radio') {
				// as RADIO button
				if (this.name!=prevname) names++;
				prevname = this.name;
				namechecked = jQuery('input[name='+this.name+']:checked').val();
				namechecked = (typeof(namechecked) == "undefined") ? false : true;
				if (this.checked==true) {
					tmpicParams += ", prodcust_" + this.name + ": '" + this.value + "'";
					// foundaltprodno += this.title+' ';
					namesselected++;
					foundarr[this.name] = true;
					found = true;
				} else if (!foundarr[this.name]) {
					if (foundflagarr[this.name]!=true && !namechecked) {
						notfound += '- '+this.title+"\n";
						foundflagarr[this.name] = true;
					}
				}
			} else { 
				// as SELECT drop down
				if (this.options[this.selectedIndex].title) {
					if (foundaltprodno) foundaltprodno += ', ';
					foundaltprodno += this.options[this.selectedIndex].value;
				}
				var value = "";
				if (this.value=='') {
					if (this.tagName=='SELECT') {
						alert(''+this.options[0].title);	// display title for the select label.
					} else {
						alert(''+this.name);
					}
					err = true;
				} else {
					found = true;
					value = this.value;
					if (this.tagName=='SELECT') {
						// value = t.options[t.selectedIndex].title;
						value = this.options[this.selectedIndex].text;
					}
				}
				tmpicParams += ", prodcust_" + this.name + ": '" + value + "'";
			}	// end of SELECT
		});
		if (namesselected<names) {
			err = true;
		}
		if (foundaltprodno!='') {
			tmpicParams += ", prodcust_altprodno: '" + foundaltprodno + "'";
		}
		
		// If not artid we test if we have alternate description and price
		if (!artid) {
			if (altdesc) {
				tmpicParams += ", prodcust_altdesc: '" + altdesc + "'";
				custcounter++;
				found = true;
			}

			if (altprice) {
				tmpicParams += ", prodcust_altprice: '" + altprice + "'";
				custcounter++;
				found = true;
			}
		}
		eval("icParams = {" + tmpicParams + "}");
		if (custcounter) {
			if (!found) err = true;
			if (err) {
				if (notfound) alert(''+notfound);
				return false;
			}
		}

		/**
			 $("#feeds").load("feeds.php", {limit: 25}, function(){ ... });
		 */
		jQuery('#shopcartcontent').load(
					'shop3/inserttocart.php',
					icParams, 
					function(responseText, textStatus, XMLHttpRequest) {
							updateOk(responseText, textStatus, XMLHttpRequest)
					});
					/*
		new Ajax.Updater('shopcartcontent', 'shop3/inserttocart.php', {
											parameters: icParams,
											onSuccess: updateOk, 
											onFailure: updateFail
										});
					*/
		
		/**
		 * If simple shopcart then update it
		 */
		if (jQuery('#shopcartcontent')==null) {
			displayCart();	// because only default cart type is displayed on insert to cart. 
		}
		// updateContentFields();
		return false;
}

/**
 * Show shoppingcart - for example on page reload
 */
function displayCart() {
		/**
		 * Update standard shoppingcart if exists
		 */
		var cont = document.getElementById('abexeroomcontainer');
		if (cont && cont.tagName!='') {
			return;	// ignore erooms
		}
		
		cont = document.getElementById('shopcartcontent');
		if (cont && cont.tagName!='') {
			jQuery('#shopcartcontent').load("shop3/inserttocart.php?displayonly=1");
		}

		cont = document.getElementById('shopcartcontenttable');
		if (cont && cont.tagName!='') {
			jQuery('#shopcartcontenttable').load("shop3/inserttocart.php?displayonlytable=1");
		}

		/**
		 * Update simple shoppingcart if exists
		 */
		var contsimple = document.getElementById('shopcartcontentsimple');
		if (contsimple && contsimple.tagName!='') {
			jQuery('#shopcartcontentsimple').load("shop3/inserttocart.php?displayonlysimple=1");
		}
    updateContentFields();
}

function loggInnToggle() {
	jQuery('#checkoutloginform').toggle(); 
	jQuery('#checkoutinfoform').toggle(); 
	jQuery('#logininfotext').toggle(); 
	return false;
}


jQuery(document).ready(function(){
	displayCart();
});


