/*function ShowInfo(popupInfo,e,position)
{
        var x = 0;
        var y = 0;

        if (!e)
        {
           if(window.event)
           {
             //Internet Explorer
             e = window.event;
           }
           else
           {
             //total failure, we have no way of referencing the event
             //alert("error");
           }
        }
        if (typeof(e.pageX)=="number")
        {
                x = e.pageX;
                y = e.pageY;
        }
        else if (typeof(e.clientX)=="number")
        {
                x = e.clientX;
                y = e.clientY;

          var badOldBrowser = ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) ||
            ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ||
            ( navigator.vendor == 'KDE' )
           if( !badOldBrowser )
           {
             if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) )
             {
               //IE 4, 5 & 6 (in non-standards compliant mode)
               x += document.body.scrollLeft;
               y += document.body.scrollTop;
             }
             else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) )
             {
               //IE 6 (in standards compliant mode)
               x += document.documentElement.scrollLeft;
               y += document.documentElement.scrollTop;
             }
           }
        }

        //alert("position "+position);
        if(position=="left")
        {
          popupInfo.style.display="block";
          popupInfo.style.left = x - 210;
          popupInfo.style.top = y - 60;
        }
        else if(position=="right")
        {
          popupInfo.style.display="block";
          popupInfo.style.left = x + 10;
          popupInfo.style.top = y - 60;
        }
        else if(position=="over")
        {
          popupInfo.style.display="block";
          popupInfo.style.left = x - 160;
          popupInfo.style.top = y - 170;
        }
        else if(position=="under")
        {
          popupInfo.style.display="block";
          popupInfo.style.left = x - 180;
          popupInfo.style.top = y + 25;
        }
        else
        {
          //alert("no pos "+position);
          popupInfo.style.display="block";
          popupInfo.style.left = x - 180;
          popupInfo.style.top = y - 180;
        }
}
function HideInfo(popupInfo,e){
        popupInfo.style.display="none";
}*/
function ShowInfo(value, e)
{
        var x = 0;
        var y = 0;

        if (!e)
        {
           if(window.event)
           {
             //Internet Explorer
             e = window.event;
           }
           else
           {
             //total failure, we have no way of referencing the event
             //alert("error");
           }
        }
        if (typeof(e.pageX)=="number")
        {
                x = e.pageX;
                y = e.pageY;
        }
        else if (typeof(e.clientX)=="number")
        {
                x = e.clientX;
                y = e.clientY;

          var badOldBrowser = ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) ||
            ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ||
            ( navigator.vendor == 'KDE' )
           if( !badOldBrowser )
           {
             if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) )
             {
               //IE 4, 5 & 6 (in non-standards compliant mode)
               x += document.body.scrollLeft;
               y += document.body.scrollTop;
             }
             else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) )
             {
               //IE 6 (in standards compliant mode)
               x += document.documentElement.scrollLeft;
               y += document.documentElement.scrollTop;
             }
           }
        }
        var position = 'under'
        //alert("position "+position);
        //alert("x "+x+" y "+y);
        if(position=="under")
        {
          document.getElementById("popupInfo").style.display="block";
          document.getElementById("popupInfo").style.left = x + 40;
          document.getElementById("popupInfo").style.top = y - 70;
        }
        value = value.toLowerCase();
        value = value.split(' ').join('_')
        //document.getElementById("popupInfo").innerHTML = "x:"+x+" y:"+y;
        document.getElementById("popupInfo").innerHTML = "<img src='/products/colors/"+value+".jpg' />";
}
function MoveInfo(value, e)
{
        var x = 0;
        var y = 0;

        if (!e)
        {
           if(window.event)
           {
             //Internet Explorer
             e = window.event;
           }
           else
           {
             //total failure, we have no way of referencing the event
             //alert("error");
           }
        }
        if (typeof(e.pageX)=="number")
        {
                x = e.pageX;
                y = e.pageY;
        }
        else if (typeof(e.clientX)=="number")
        {
                x = e.clientX;
                y = e.clientY;

          var badOldBrowser = ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) ||
            ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ||
            ( navigator.vendor == 'KDE' )
           if( !badOldBrowser )
           {
             if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) )
             {
               //IE 4, 5 & 6 (in non-standards compliant mode)
               x += document.body.scrollLeft;
               y += document.body.scrollTop;
             }
             else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) )
             {
               //IE 6 (in standards compliant mode)
               x += document.documentElement.scrollLeft;
               y += document.documentElement.scrollTop;
             }
           }
        }
        var position = 'under'
        //alert("position "+position);
        //alert("x "+x+" y "+y);
        if(position=="under")
        {
          document.getElementById("popupInfo").style.display="block";
          document.getElementById("popupInfo").style.left = x + 40;
          document.getElementById("popupInfo").style.top = y - 70;
        }
        //document.getElementById("popupInfo").innerHTML = "x:"+x+" y:"+y;
}
function HideInfo(value){
        document.getElementById("popupInfo").style.display="none";
}

function js_submit_amount(prod_id, amount, e) //kunna trycka enter när man vill ändra antal
{
 if (e.keyCode == 13) //enter har tryckts ner
 {
   ajaxAddProduct(prod_id);
 }
}




var xmlHttp;
var xmlHttp2;
var div_name='';
var div_name2='';

function stateChanged()
{
 //alert(xmlHttp.readyState+" "+xmlHttp.readyState+" "+div_name)
 if ((xmlHttp.readyState==4 || xmlHttp.readyState=="complete") && div_name!='')
 {
   document.getElementById(div_name).innerHTML=xmlHttp.responseText;
 }
}
function stateChanged2()
{
 //alert(xmlHttp.readyState+" "+xmlHttp.readyState+" "+div_name)
 if ((xmlHttp2.readyState==4 || xmlHttp2.readyState=="complete") && div_name2!='')
 {
   document.getElementById(div_name2).innerHTML=xmlHttp2.responseText;
 }
}

function GetXmlHttpObject()
{
 var objXMLHttp=null;

 if (window.XMLHttpRequest)
 {
   objXMLHttp=new XMLHttpRequest();
 }
 else if (window.ActiveXObject)
 {
   objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 return objXMLHttp;
}



          function getexpirydate( nodays){
          var UTCstring;
          Today = new Date();
          nomilli=Date.parse(Today);
          Today.setTime(nomilli+nodays*24*60*60*100);
          UTCstring = Today.toUTCString();
          return UTCstring;
          }

          function getcookie(cookiename) {
           var cookiestring=""+document.cookie;
           var index1=cookiestring.indexOf(cookiename);
           if (index1==-1 || cookiename=="") return "";
           var index2=cookiestring.indexOf(';',index1);
           if (index2==-1) index2=cookiestring.length;
           return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
          }

          function setcookie(name,value,duration){
          cookiestring=name+"="+escape(value)+";EXPIRES="+getexpirydate(duration*1);
          document.cookie=cookiestring;
          if(!getcookie(name)){
          return false;
          }
          else{
          return true;
          }
          }


          function MM_swapImgRestore() { //v3.0
            var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
          }

          function MM_preloadImages() { //v3.0
            var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
              var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
              if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
          }

          function MM_findObj(n, d) { //v4.01
            var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
              d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
            if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
            for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
            if(!x && d.getElementById) x=d.getElementById(n); return x;
          }

          function MM_swapImage() { //v3.0
            var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
             if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
          }






var url_addProductToBasket = 'aj_varukorg_add.php';
var url_removeProductFromBasket = 'aj_varukorg_remove.php';
var txt_totalPrice = 'Total: ';

var ajaxObjects = new Array();

function showAjaxBasketContent(ajaxIndex,amount)
{
        if(amount<1)
        {
         amount=1;
        }

        // referens till varukorgstabellen
        var itemBox = document.getElementById('varukorg_items');

        var productItems = ajaxObjects[ajaxIndex].response.split('|||');
        alert(productItems);        // explode ajaxresultatet

        //kontrollera data
        if(productItems[0] && productItems[1])
        {
          if(document.getElementById('varukorg_items_row' + productItems[0]))   // Produkt_id finns redan i varukorgen - plussa på
          {
                  var row = document.getElementById('varukorg_items_row' + productItems[0]);
                  var items = row.cells[0].innerHTML /1;
                  items = parseInt(items) + parseInt(amount);
                  row.cells[0].innerHTML = items;
          }
          else    // Produkten finns inte i varukorgen, lägg till
          {

                  var tr = itemBox.insertRow(-1);
                  tr.id = 'varukorg_items_row' + productItems[0]

                  var td = tr.insertCell(-1);
                  td.innerHTML = amount;         // Antal

                  var td = tr.insertCell(-1);
                  td.innerHTML = 'x';         // x

                  var td = tr.insertCell(-1);
                  td.innerHTML = "<a href='product.php?id="+productItems[0]+"'>"+productItems[1]+"</a>";         // Namn

                  var td = tr.insertCell(-1);
                  td.innerHTML = '';         // tomt

                  var td = tr.insertCell(-1);
                  //td.style.textAlign = 'right';
                  //td.style.display = 'none';
                  td.innerHTML = productItems[2];         // Pris

                  var td = tr.insertCell(-1);
                  var a = document.createElement('A');
                  td.appendChild(a);
                  a.href = '#';
                  a.onclick = function(){ removeProductFromBasket(productItems[0]); };
                  var img = document.createElement('IMG');
                  img.src = 'trashcan1.gif';
                  img.width = "10";
                  img.height = "15";
                  img.border = "0";
                  a.appendChild(img);
          }
        }

        updateTotalPrice();

        ajaxObjects[ajaxIndex] = false;

        window.setTimeout('hide_cart_progress()',700);

        document.getElementById("nothing_in_cart_info").style.display = "none";

}

function updateTotalPrice(tableId)
{
   var itemBox = document.getElementById('varukorg_items');

   // Calculating total price and showing it below the table with basket items
   var totalPrice = 0;
   var freight_added = 0;
   if(document.getElementById('varukorg_totalprice'))
   {

      var loop = itemBox.rows.length - 1;
      alert(loop);
      for(var no=1;no<=loop;no++)                                                  //   document.getElementById('cart_price_holder-'+no).value
      {
        alert('test');
		if(document.getElementById('varukorg_items2_'+no)) //Just nu ID, måste ha en counter
		{
			var itemBox2 = document.getElementById('varukorg_items2_'+no);
            var itemBox3 = document.getElementById('varukorg_items3_'+no);

			if(itemBox2.rows[1])
			{
				alert(itemBox2.rows[0].cells[3].innerHTML);
				if(itemBox2.rows[0].cells[3].innerHTML == 'Fraktkonstnad')
				{
					alert('ja');
					totalPrice = totalPrice + (itemBox2.rows[0].cells[1].innerHTML.replace(/[^0-9]/g) * itemBox2.rows[0].cells[5].innerHTML);
				}
				else
				{
					alert('nej');
					totalPrice = totalPrice + (itemBox2.rows[0].cells[1].innerHTML.replace(/[^0-9]/g) * itemBox2.rows[3].cells[3].innerHTML);
				}
				//alert(totalPrice);
			}
		}
         /*if(itemBox.rows[no].cells[2].innerHTML=='Frakt')
         {
           freight_added=1;
         } */
      }

      /*if(freight_added==0)
      {
         //ajaxObjects[999]="2729|||Frakt|||49.00";
         //showAjaxBasketContent(999,1)
      } */
      document.getElementById('varukorg_totalprice').innerHTML = '<b>'+txt_totalPrice + totalPrice.toFixed(2) + '</b>';
   }
}

function removeProductFromBasket(tableId, productId)
{
    var productRow = document.getElementById('varukorg_items2_row_' + tableId);
    var productRow2 = document.getElementById('varukorg_items2_row_' + tableId +'_2');
    var productRow3 = document.getElementById('varukorg_items3_row_' + tableId);
    var numberOfItemCell = productRow.cells[1];

    if(numberOfItemCell.innerHTML == '1')
    {
  		productRow.parentNode.removeChild(productRow);
  		productRow2.parentNode.removeChild(productRow2);
  		productRow3.parentNode.removeChild(productRow3);
    }
    else
    {
      numberOfItemCell.innerHTML = numberOfItemCell.innerHTML/1 - 1;
    }
    ajaxRemoveProduct(productId);
    updateTotalPrice(tableId);

}

function ajaxValidateRemovedProduct(ajaxIndex)
{
  if(ajaxObjects[ajaxIndex].response!='OK')alert('Error while removing product from the database');
}

function ajaxRemoveProduct(productId)
{
        var ajaxIndex = ajaxObjects.length;
        ajaxObjects[ajaxIndex] = new sack();
        ajaxObjects[ajaxIndex].requestFile = url_removeProductFromBasket + '?prod_id=' + productId;        // Saving product in this file
        ajaxObjects[ajaxIndex].onCompletion = function(){ ajaxValidateRemovedProduct(ajaxIndex); };        // Specify function that will be executed after file has been found
        ajaxObjects[ajaxIndex].runAJAX();                // Execute AJAX function
}

function ajaxAddProduct(productId)
{
		var amount = 1;
        var ajaxIndex = ajaxObjects.length;
        ajaxObjects[ajaxIndex] = new sack();
        ajaxObjects[ajaxIndex].requestFile = url_addProductToBasket + '?prod_id=' + productId + '&amount=' + amount;        // Saving product in this file
        ajaxObjects[ajaxIndex].onCompletion = function(){ showAjaxBasketContent(ajaxIndex, amount); };        // Specify function that will be executed after file has been found
        ajaxObjects[ajaxIndex].runAJAX();                // Execute AJAX function
}




function show_search_result()
{
 if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 {
 document.getElementById("main_holder").innerHTML=xmlHttp.responseText
 }
}

/*
function Search_Clear(element)
{
  if (element.value.indexOf("Sökord") == 0)
  {
     element.value = "";
  }
  else if (element.value.indexOf("Hakusana") == 0)
  {
     element.value = "";
  }
}  */

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( name ) {

var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) &&
( name != document.cookie.substring( 0, name.length ) ) )
{
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ";", len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}




function show_cart_progress(e)
{
   var x = 0;
   var y = 0;
   //var e = arguments[0];

   var show_div = document.getElementById("cart_progress");

        if (!e)
        {
           if(window.event)
           {
             //Internet Explorer
             e = window.event;
           }
           else
           {
             //total failure, we have no way of referencing the event
             //alert("error");
           }
        }
        if (typeof(e.pageX)=="number")
        {
                x = e.pageX;
                y = e.pageY;
        }
        else if (typeof(e.clientX)=="number")
        {
                x = e.clientX;
                y = e.clientY;

          var badOldBrowser = ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) ||
            ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ||
            ( navigator.vendor == 'KDE' )
           if( !badOldBrowser )
           {
             if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) )
             {
               //IE 4, 5 & 6 (in non-standards compliant mode)
               x += document.body.scrollLeft;
               y += document.body.scrollTop;
             }
             else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) )
             {
               //IE 6 (in standards compliant mode)
               x += document.documentElement.scrollLeft;
               y += document.documentElement.scrollTop;
             }
           }
        }

        //document.getElementById("popupInfo").style.display="block";



   show_div.style.display = "block";
   //show_div.style.left = x - 64;
   //show_div.style.top = y + 24;
}
function hide_cart_progress()
{
   var hide_div = document.getElementById("cart_progress");
   hide_div.style.display = "none";
}

function Search_Clear(element)
{
  if (element.value.indexOf(" Sökord..") == 0)
  {
     element.value = "";
  }
  else if (element.value.indexOf(" Hakusana..") == 0)
  {
     element.value = "";
  }
}

/************************************
  black toner guide
************************************/

function update_guide(holder, ink_type, cat_id, fam_id)
{
 xmlHttp=GetXmlHttpObject()
 div_name=holder;
 if (xmlHttp==null)
 {
   //alert ("Browser does not support HTTP Request")
   return
 }
 var url="aj_update_toner_guide.php";
 url=url+"?ink_type=" + ink_type +"&category_id=" + cat_id + "&fam_id=" + fam_id + "";

 //alert (url + ' ' + div_name);

 xmlHttp.onreadystatechange=stateChanged;
 xmlHttp.open("GET",url,true);
 xmlHttp.send(null);
 //div_name='';
}

/*******************************************
   Betalsätt
*******************************************/

crir = {
        init: function() {
                arrLabels = document.getElementsByTagName('label');

                searchLabels:
                for (var i=0; i<arrLabels.length; i++) {
                        // get the input element based on the for attribute of the label tag
                        if (arrLabels[i].getAttributeNode('for') && arrLabels[i].getAttributeNode('for').value != '') {
                                labelElementFor = arrLabels[i].getAttributeNode('for').value;
                                inputElement = document.getElementById(labelElementFor);
                        }
                        else {
                                continue searchLabels;
                        }

                        inputElementClass = inputElement.className;

                        // if the input is specified to be hidden intiate it
                        if (inputElementClass == 'crirHiddenJS') {
                                inputElement.className = 'crirHidden';

                                inputElementType = inputElement.getAttributeNode('type').value;

                                // add the appropriate event listener to the input element
                                if (inputElementType == "checkbox") {
                                        inputElement.onclick = crir.toggleCheckboxLabel;
                                }
                                else {
                                        inputElement.onclick = crir.toggleRadioLabel;
                                }

                                // set the initial label state
                                if (inputElement.checked) {
                                        if (inputElementType == 'checkbox') { arrLabels[i].className = 'checkbox_checked'}
                                        else { arrLabels[i].className = 'radio_checked' }
                                }
                                else {
                                        if (inputElementType == 'checkbox') { arrLabels[i].className = 'checkbox_unchecked'}
                                        else { arrLabels[i].className = 'radio_unchecked' }
                                }
                        }
                        else if (inputElement.nodeName != 'SELECT' && inputElement.getAttributeNode('type').value == 'radio') { // this so even if a radio is not hidden but belongs to a group of hidden radios it will still work.
                                arrLabels[i].onclick = crir.toggleRadioLabel;
                                inputElement.onclick = crir.toggleRadioLabel;
                        }
                }
        },

        findLabel: function (inputElementID) {
                arrLabels = document.getElementsByTagName('label');

                searchLoop:
                for (var i=0; i<arrLabels.length; i++) {
                        if (arrLabels[i].getAttributeNode('for') && arrLabels[i].getAttributeNode('for').value == inputElementID) {
                                return arrLabels[i];
                                break searchLoop;
                        }
                }
        },

        toggleCheckboxLabel: function () {
                labelElement = crir.findLabel(this.getAttributeNode('id').value);

                if(labelElement.className == 'checkbox_checked') {
                        labelElement.className = "checkbox_unchecked";
                }
                else {
                        labelElement.className = "checkbox_checked";
                }
        },

        toggleRadioLabel: function () {
                clickedLabelElement = crir.findLabel(this.getAttributeNode('id').value);

                clickedInputElement = this;
                clickedInputElementName = clickedInputElement.getAttributeNode('name').value;

                arrInputs = document.getElementsByTagName('input');

                // uncheck (label class) all radios in the same group
                for (var i=0; i<arrInputs.length; i++) {
                        inputElementType = arrInputs[i].getAttributeNode('type').value;
                        if (inputElementType == 'radio') {
                                inputElementName = arrInputs[i].getAttributeNode('name').value;
                                inputElementClass = arrInputs[i].className;
                                // find radio buttons with the same 'name' as the one we've changed and have a class of chkHidden
                                // and then set them to unchecked
                                if (inputElementName == clickedInputElementName && inputElementClass == 'crirHidden') {
                                        inputElementID = arrInputs[i].getAttributeNode('id').value;
                                        labelElement = crir.findLabel(inputElementID);
                                        labelElement.className = 'radio_unchecked';
                                }
                        }
                }

                // if the radio clicked is hidden set the label to checked
                if (clickedInputElement.className == 'crirHidden') {
                        clickedLabelElement.className = 'radio_checked';
                }
        },

        addEvent: function(element, eventType, doFunction, useCapture){
                if (element.addEventListener)
                {
                        element.addEventListener(eventType, doFunction, useCapture);
                        return true;
                } else if (element.attachEvent) {
                        var r = element.attachEvent('on' + eventType, doFunction);
                        return r;
                } else {
                        element['on' + eventType] = doFunction;
                }
        }
}

crir.addEvent(window, 'load', crir.init, false);


function deliveryDate()
{
	var interval = parseInt(document.add_product.interval.options[document.add_product.phone_block.selectedIndex].value);
	var today = new Date();
	if(interval > 12)
	{
		var delivery = new Date();
		delivery_date = delivery.setDate(delivery.getDate()+interval);
	}
	else
	{
		var delivery = new Date();
		var delivery_date = delivery.setDate(delivery.getMonth()+interval);
	}
    var message = "Din andra leverans kommer att levereras till dig runt den";
	document.getElementById('delivery_text').innerHTML=message+" "+delivery_date;
	document.getElementById('delivery').value = delivery_date;
}

function toggleToplist() {
	$('#toplistextension').toggle('slow');
}

function showCartButton() {
	$('#addCartButton').fadeIn('fast');
}

function showBig(productId) {
	window.open('/productImage.php?picId=' + productId);
}