
/* Javascript right function */
	function Right(str, n)
	/***
			IN: str - the string we are RIGHTing
				n - the number of characters we want to return

			RETVAL: n characters from the right side of the string
	***/
	{
			if (n <= 0)     // Invalid bound, return blank string
			   return "";
			else if (n > String(str).length)   // Invalid bound, return
			   return str;                     // entire string
			else { // Valid bound, return appropriate substring
			   var iLen = String(str).length;
			   return String(str).substring(iLen, iLen - n);
			}
	}

/* Sets price level and updates div that's containing products for current filter */
	function ws_setPriceLevel(numPriceID,numMenuID,strAllProducts){
		
		// set currently selected Price ID
			document.webshopFilter.PRICE_ID.value = numPriceID;
			document.webshopFilter.ALL_PRODUCTS.value = strAllProducts;

		// update 
			updateWebshopItems();

	}

/* Swap color filter graphic and update product list with ajax */
	function swapSelectColor(img, objFieldName){

		// set field to opposite of current value
			var field = document.getElementById(objFieldName);
			var val = new Number(1);
			val = field.value;
			if (val == 1){
				field.value = 0;
				img.src = "images/webshop_color.gif";
			} else {
				field.value = 1;
				img.src = "images/webshop_color_selected.gif";
			}

		// update contents of webshop-items
			updateWebshopItems();
			
	}

/* Return selected color variables in querystring form */
	function getSelectedColors(){
		var strOut = new String;
		strOut = "&FIELD04_X4=" + document.getElementById("FIELD04_X4").value;
		strOut = strOut + "&FIELD05_X5=" + document.getElementById("FIELD05_X5").value;
		strOut = strOut + "&FIELD07_X7=" + document.getElementById("FIELD07_X7").value;
		strOut = strOut + "&FIELD08_X8=" + document.getElementById("FIELD08_X8").value;
		strOut = strOut + "&FIELD09_X9=" + document.getElementById("FIELD09_X9").value;
		strOut = strOut + "&FIELD10_X10=" + document.getElementById("FIELD10_X10").value;
		strOut = strOut + "&FIELD11_X11=" + document.getElementById("FIELD11_X11").value;
		return strOut;
	}

/* Updates webshop items */
	function updateWebshopItems(){
		setAjax("document.asp?ajax=1&menu=" + document.webshopFilter.MENU_ID.value + "&price_level=" + document.webshopFilter.PRICE_ID.value + getSelectedColors() + "&DIRECTION=" + document.webshopFilter.PRICE_ORDER.value + "&STYLE=" + document.webshopFilter.STYLE.value + "&ALL_PRODUCTS=" + document.webshopFilter.ALL_PRODUCTS.value, "webshop-items" );
	}


/* Swaps small and big image on product display */
	function swapImage(which){
		var oldImage = new String;
		var oldImage = document.getElementById("prod_img_main").src;
		var newImage = new String;
		newImage = which.src;


		// set which's image to the main container
			var pos=newImage.lastIndexOf("/");
			pos=newImage.indexOf("_",pos);
			document.getElementById("prod_img_main").src = "./prod_images/" + document.f1.PRODUCT_ID.value + "_c" + newImage.substr(pos+2,newImage.length);

		// set main container's image to which
			pos=oldImage.lastIndexOf("/");
			pos=oldImage.indexOf("_",pos);
			which.src = "./prod_images/" + document.f1.PRODUCT_ID.value + "_b" + oldImage.substr(pos+2,oldImage.length);
			
	}

/* Check that field for searchvalue contains anything */
	function checkSearch(){
		if (document.SEARCH.search.value == '')
		{
			alert("Vennligst skriv inn søkeord først.");
			return false;
		}
		else {
			document.SEARCH.submit();
		}
	}

/* Handle "Help me choose" */
	function helpMeChoose(){
		document.FORM1.submit();
	}

/* Webshop shopping preferences choices */
	function wsSetURL(which){
		document.shop_basket_full.cust_type_url.value = which.value;
	}
	function wsProceedCheckout(){
		if (document.shop_basket_full.cust_type_url.value == ''){
			alert("Du må først velge en måte å fortsette handelen på.");
		} else {
			//alert(document.shop_basket_full.cust_type_url.value);
			document.location = document.shop_basket_full.cust_type_url.value;
		}
	}
	function wsBasket(){
		document.shop_basket_full.REDIRECT.value = "default.asp?menu="+document.shop_basket_full.MENU.value+"&view=shop_basket_full";
		wsSubmitAddress("a");
	}

/* Checkout */

	/* empty "korttekst" */
	function emptyMessage(boolDoIt,strIdTemplate)
	{
		if (!boolDoIt) return

		for (var i=1;i<6;i++)
		{
			document.getElementById(strIdTemplate+i).value = "";
		}
	}

	/* show/hide correct pay type */
	function PayTypeCard(orly)
	{
		if (!orly) return;

		document.getElementById("PayTypeCard").style.display = "block";
		document.getElementById("PayTypeInvoice").style.display = "none";

		wsSubmitAddress('PAYMENT');
	}
	function PayTypeInvoice(orly)
	{
		if (!orly) return;

		document.getElementById("PayTypeCard").style.display = "none";
		document.getElementById("PayTypeInvoice").style.display = "block";

		wsSubmitAddress('PAYMENT');
	}

/* Submit webshop counter for updating (ie: doesn't submit for sale, just updating info on page */
	function wsSubmitAddress(anchor){
		document.shop_basket_full.CMD.value = 'ADDRESS';
		document.shop_basket_full.action='default.asp?menu=56&view=shop_counter#'+anchor;
		document.shop_basket_full.submit();
	}

/* Submit shop - validate and stuff */
	function wsPay(){
		if (validate_input() == "TRUE"){
			document.shop_basket_full.CMD.value="SUBMIT";
			document.shop_basket_full.submit();
		}
	}

/* Copy address from previous */
	function wsCopyAddress(anchor){
		try
		{
			document.shop_basket_full[anchor+'_COPY_ADDRESS_INDICATOR'].value = 1;
		}
		catch (a)
		{
		}
		wsSubmitAddress(anchor);
	}

/* Text suggestions for webshop */
	function text_suggestion(strField){
		var url="aiai_text_suggestion.asp?field=" + strField;
		window.open(url, "", "fullscreen=no,toolbar=no,status=yes,menubar=no,scrollbars=yes,resizable=no,directories=no,location=no,width=450,height=300,left=100,top=100")
	}	

/* Generic popup */
	function popup(url){
		window.open(url, "", "fullscreen=no,toolbar=no,status=yes,menubar=no,scrollbars=yes,resizable=no,directories=no,location=no,width=640,height=400,left=100,top=100")
	}	

/* Login - forgotten passord */
	function forgottenPassword(next){
		if (document.LOGIN.user.value == ''){
			alert("Du må skrive inn e-post adresse for å få tilsendt passord.")
			return false;
		}
		else {
			document.location="default.asp?view=login&menu=" + document.LOGIN.MENU.value + "&cmd=sendpassword&email=" + document.LOGIN.user.value + "&next=" + next;
		}
	}

/* Check if correct number of fields are filled in when sending tips */
	function checkTips(){
		if ((document.FORM1.MY_EMAIL.value == '') || (document.FORM1.MY_NAME.value == '') || (document.FORM1.FRIEND_EMAIL.value == '') || (document.FORM1.FRIEND_NAME.value == '')){
			alert("Du må fylle ut alle feltene.");
			return false;
		}
		else {
			document.FORM1.submit();
		}
	}

/* Webshop basket update function - being used in shop_basket_full.xsl */
	function wsUpdateBasket(action,product_id,num_units,price,order_line_id,view_type,view,menu,qs){
		// any number entered in number of units?
		if (isNaN(num_units) || num_units < 1)
		{
			alert("Antall må settes til 1 eller mer. For å fjerne et produkt fra handlekurven, trykk 'Slett'");
			return;
		}
		document.SUBMIT.action.value = action;
		document.SUBMIT.product_id.value = product_id;
		document.SUBMIT.num_units.value = num_units;
		document.SUBMIT.price.value = price;
		document.SUBMIT.order_line_id.value = order_line_id;
		document.SUBMIT.view_type.value = view_type;
		document.SUBMIT.view.value = view;
		document.SUBMIT.menu.value = menu;
		document.SUBMIT.qs.value = qs;
		document.SUBMIT.submit()
	}

/* Toggle visible calendar */
	function wsToggleCalendar(id){
		var e = document.getElementById(id);
		if(e.style.display == 'none')
		e.style.display = 'block';
		else
		e.style.display = 'none';
	}

/* Valid date? (for users who have to input date manually */
function validateDate( strValue ) {
	/************************************************
	DESCRIPTION: Validates that a string contains only
		valid dates with 2 digit month, 2 digit day,
		4 digit year. Date separator can be ., -, or /.
		Uses combination of regular expressions and
		string parsing to validate date.
		Ex. dd.mm.yyyy

	PARAMETERS:
	   strValue - String to be tested for validity

	RETURNS:
	   True if valid, otherwise false.

	REMARKS:
	   Avoids some of the limitations of the Date.parse()
	   method such as the date separator character.
	*************************************************/
  var objRegExp = /^\d{1,2}(\.)\d{1,2}\1\d{4}$/
 
  //check to see if in correct format
  if(!objRegExp.test(strValue))
    return false; //doesn't match pattern, bad date
  else{
    var strSeparator = strValue.substring(2,3) 
    var arrayDate = strValue.split(strSeparator); 
    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, 
                        '04' : 30,'05' : 31,
                        '06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,
                        '10' : 31,'11' : 30,'12' : 31}
    var intDay = parseInt(arrayDate[0],10); 

	//check if month value and day value agree
    if(arrayLookup[arrayDate[1]] != null) {
      if(intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
        return true; //found in lookup table, good date
    }
    
    //check for February (bugfix 20050322)
    //bugfix  for parseInt kevin
    //bugfix  biss year  O.Jp Voutat
    var intMonth = parseInt(arrayDate[1],10);
    if (intMonth == 2) { 
       var intYear = parseInt(arrayDate[2]);
       if (intDay > 0 && intDay < 29) {
           return true;
       }
       else if (intDay == 29) {
         if ((intYear % 4 == 0) && (intYear % 100 != 0) || 
             (intYear % 400 == 0)) {
              // year div by 4 and ((not div by 100) or div by 400) ->ok
             return true;
         }   
       }
    }
  }  
  return false; //any other values, bad date
}
