/*
// ///////////////////////////
// isdefined v1.0
// 
// Check if a javascript variable has been defined.
// 
// Author : Jehiah Czebotar
// Website: http://www.jehiah.com
// Usage  : alert(isdefined('myvar'));
// ///////////////////////////
*/
function addEvent(obj, evType, fn){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, true);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    return false;
  }
}

  function checkCR(evt) {

    var evt  = (evt) ? evt : ((event) ? event : null);

    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);

    if ((evt.keyCode == 13) && (node.type=="text")) { return false;}

  }

  document.onkeypress = checkCR;
  

function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}



function onPageLoad()
{ 
	toggleAnimation(false);
	
	if (typeof(repair) == 'function') {
		repair();
	}
	
	if (window.antalVare ) {
		if (antalVare > 0) {
			toggleBasket(true);
		}		
	}
	if (document.location.href == "http://www.peterspris.dk/") {
		//Nothing
	} else {
	if (typeof(toggleCompareCheckmark) == 'function') {
		//toggleCompareCheckmark('0');
	}
	}
	if (window.antalVare ) {
		if (antalVare > 0) {
			toggleBasket(true);
		}		
	}
// Check for forms
	if (typeof(document.forms['form'])=='object') {
//Set focus on 'navn' on addressform
		if (typeof(document.forms['form'])=='object') {
			if (typeof(document.forms['form'].elements['navn'])=='object')	{
				setfocus(document.forms['form'].elements['navn']);
			}			
		}
	}
	
	if (typeof(document.getElementById('compare'))=='object') {
// on compare page, check searchbox state
// 		refresh(0);		
	}
	
// Set focus on 'cardnum' on ccipage	
	if (typeof(document.forms['quickpay_pay'])=='object') {
		if (typeof(document.forms['quickpay_pay'].elements['cardnum'])=='object')	{
			document.forms['quickpay_pay'].elements['cardnum'].focus();
		}
	}
	if (typeof(validateBidItems)=='function') {
		validateBidItems(document.forms['update']);
	}
} 



/*
 * Copyright 2006 SitePoint Pty. Ltd, www.sitepoint.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS;
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

function Ajax() {
  this.req = null;
  this.url = null;
  this.status = null;
  this.statusText = '';
  this.method = 'GET';
  this.async = true;
  this.dataPayload = null;
  this.readyState = null;
  this.responseText = null;
  this.responseXML = null;
  this.handleResp = null;
  this.responseFormat = 'text', // 'text', 'xml', 'object'
  this.mimeType = null;
  this.headers = [];

  
  this.init = function() {
    var i = 0;
    var reqTry = [ 
      function() { return new XMLHttpRequest(); },
      function() { return new ActiveXObject('Msxml2.XMLHTTP') },
      function() { return new ActiveXObject('Microsoft.XMLHTTP' )} ];
      
    while (!this.req && (i < reqTry.length)) {
      try { 
        this.req = reqTry[i++]();
      } 
      catch(e) {}
    }
    return true;
  };
  this.doGet = function(url, hand, format) {
    this.url = url;
    this.handleResp = hand;
    this.responseFormat = format || 'text';
    this.doReq();
  };
  this.doPost = function(url, dataPayload, hand, format) {
    this.url = url;
    this.dataPayload = dataPayload;
    this.handleResp = hand;
    this.responseFormat = format || 'text';
    this.method = 'POST';
    this.doReq();
  };
  this.doReq = function() {
    var self = null;
    var req = null;
    var headArr = [];
    
    if (!this.init()) {
      alert('Could not create XMLHttpRequest object.');
      return;
    }
    req = this.req;
    req.open(this.method, this.url, this.async);
    if (this.method == "POST") {
      this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    if (this.method == 'POST') {
      req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    self = this;
    req.onreadystatechange = function() {
      var resp = null;
      self.readyState = req.readyState;
      if (req.readyState == 4) {
        
        self.status = req.status;
        self.statusText = req.statusText;
        self.responseText = req.responseText;
        self.responseXML = req.responseXML;
        
        switch(self.responseFormat) {
          case 'text':
            resp = self.responseText;
            break;
          case 'xml':
            resp = self.responseXML;
            break;
          case 'object':
            resp = req;
            break;
        }
        
        if (self.status > 199 && self.status < 300) {
          if (!self.handleResp) {
            alert('No response handler defined ' +
              'for this XMLHttpRequest object.');
            return;
          }
          else {
            self.handleResp(resp);
          }
        }
        
        else {
          self.handleErr(resp);
        }
      }
    }
    req.send(this.dataPayload);
  };
  this.abort = function() {
    if (this.req) {
      this.req.onreadystatechange = function() { };
      this.req.abort();
      this.req = null;
    }
  };
  this.handleErr = function() {
    var errorWin;
    // Create new window and display error
    try {
      errorWin = window.open('', 'errorWin');
      errorWin.document.body.innerHTML = this.responseText;
    }
    // If pop-up gets blocked, inform user
    catch(e) {
      alert('An error occurred, but the error message cannot be' +
      ' displayed because of your browser\'s pop-up blocker.\n' +
      'Please allow pop-ups from this Web site.');
    }
  };
  this.setMimeType = function(mimeType) {
    this.mimeType = mimeType;
  };
  this.setHandlerResp = function(funcRef) {
    this.handleResp = funcRef;
  };
  this.setHandlerErr = function(funcRef) {
    this.handleErr = funcRef; 
  };
  this.setHandlerBoth = function(funcRef) {
    this.handleResp = funcRef;
    this.handleErr = funcRef;
  };
  this.setRequestHeader = function(headerName, headerValue) {
    this.headers.push(headerName + ': ' + headerValue);
  };
  
}


function toggleAnimation(running) {
	var myAjaxLoader = document.getElementById('ajax-loader');
	varURL='<img src="/images/generic/ajax-loader.gif" width="58">';

	if (running) {
		varURL='<input type="image" src="/images/generic/ajax-loader_active.gif" width="58" id="soeg" disabled />';
	} else {
		//varURL='<img src="/images/generic/ajax-loader_inactive.gif" width="16">';
		if (document.forms['searchBox'] != null) {
			catid= document.forms['searchBox'].elements['catid'].value;
		} else {
			catid = '*';
		}
		if (catid=='*') {
			varURL = '';
			//alert('catid is nill');
		} else {
			varURL='<input type="image" src="/images/da/bn_search.gif" width="58" id="soeg" />';
			
		}
	}
	
	
	element = document.getElementById('ajax-loader');
	if (element==null) {
		return;
	}
	if (element.firstChild) {
		element.removeChild(element.firstChild);
	}
	element.innerHTML=varURL;

}


function toggleCompareLinks(active) {
	toggleListCompare(active);
	toggleCompareTopNav(active);
}



// The var docForm should be a reference to a <form>

function formData2QueryString(docForm) {

    var submitContent = '';
    var formElem;
    var lastElemName = '';
    
    for (i = 0; i < docForm.elements.length; i++) {
        
        formElem = docForm.elements[i];
        switch (formElem.type) {
            // Text fields, hidden form elements
            case 'text':
            case 'hidden':
            case 'password':
            case 'textarea':
            case 'select-one':
                submitContent += formElem.name + '=' + escape(formElem.value) + '&'
                break;
                
            // Radio buttons
            case 'radio':
                if (formElem.checked) {
                    submitContent += formElem.name + '=' + escape(formElem.value) + '&'
                }
                break;
                
            // Checkboxes
            case 'checkbox':
                if (formElem.checked) {
                    // Continuing multiple, same-name checkboxes
                    if (formElem.name == lastElemName) {
                        // Strip of end ampersand if there is one
                        if (submitContent.lastIndexOf('&') == submitContent.length-1) {
                            submitContent = submitContent.substr(0, submitContent.length - 1);
                        }
                        // Append value as comma-delimited string
                        submitContent += ',' + escape(formElem.value);
                    }
                    else {
                        submitContent += formElem.name + '=' + escape(formElem.value);
                    }
                    submitContent += '&';
                    lastElemName = formElem.name;
                }
                break;
                
        }
    }
    // Remove trailing separator
    submitContent = submitContent.substr(0, submitContent.length - 1);
    return submitContent;
}


var updateOptionPrice = function(str) {
	var parameters = str.split('|');
	var productID = Number(parameters[0]);
	var priceValue = Number(parameters[1]);	
	var listPriceValue = Number(parameters[2]);

/* First setup the option price element */
	var theOptionPriceElement = document.getElementById('optionprice'+productID);	

	if (theOptionPriceElement.firstChild) {
		theOptionPriceElement.removeChild(theOptionPriceElement.firstChild);
	}
		
	varOptionPrice = new NumberFormat(priceValue);
	varOptionPrice.setSeparators(true,'.',',');
	
	theOptionPriceElement.innerHTML=varOptionPrice.toFormatted();
	
/* Now update the total price */
	var theTotalPriceElement = document.getElementById('totalprice'+productID);	

	if (theTotalPriceElement.firstChild) {
		theTotalPriceElement.removeChild(theTotalPriceElement.firstChild);
	}
	calcTotalPrice = listPriceValue+priceValue;
	totalPrice = new NumberFormat(calcTotalPrice);
	totalPrice.setSeparators(true,'.',',');
	
	theTotalPriceElement.innerHTML=totalPrice.toFormatted();
	
	var theFormName = 'product' + productID;

	document.forms[theFormName].elements['price'].value = calcTotalPrice;

	return;
}


var selectedOptions = new Array();

function optionchange(product,optionid,value) {

/* Find square bracets in the parameter */
	var idRegEx = /\[\d+\]/g;	
	var idArray=product.match(idRegEx);
/* Remove the square brackets to leave the ids as numbers */
	var productID = idArray[0].replace(/\[|\]/g,'');
	var optionNo = idArray[1].replace(/\[|\]/g,'');

/* Create new array */
    if ( typeof( selectedOptions[productID] ) == 'undefined' ) {
		selectedOptions[productID] = new Array();
	}
	selectedOptions[productID][optionNo] = value;

	//alert(' All options:' + selectedOptions[productID]);
	ajax.doGet('/getOptionPrice.php?optionid='+selectedOptions[productID],updateOptionPrice);
	
	return;
	
	optionCookie = Cookie.get("option");
	value = unescape(optionCookie.getValue());
	if ( value=='undefined' ) value='';

	var newValue;
	if (value.match(product) ) {
		var theStartPos=value.indexOf(product);
		var theNewString=(product + "=" + optionid);
		var theOldString=value.substring(theStartPos, theNewString.length+1);
//		alert('Startpos=' + theStartPos + ' Length=' + theNewString.length + ' Old:[' + theOldString + "] New:" + theNewString);
		newValue = value.replace(theOldString, theNewString) ;
	} else {
		newValue = value + "(" + product + "=" + optionid + ")";
//		alert ('No match' + newValue);
	}
	alert ('Value=' + value + "\nNew=" + newValue);
	optionCookie.setValue(newValue);
	optionCookie.save();

return;
	window.location.reload();
}



function movepic(img_name,img_src) {
//alert (typeof(document[img_name]));
	if (typeof(document[img_name]) == 'object') {
		document[img_name].src=img_src;
	}
}


function Cookie() {
        var name, value, expires, path="/", domain, secure=false;
        this.setName = function(sName){ name=sName; }
        this.getName = function(){ return name; }
        this.getValue = function(){
            return unescape(
                (value instanceof Array)?
                    value.join("&"):
                    value
            );
        }

        this.setValue = function(sValue){ value=escape(sValue); }
        this.add = function(key, val){
            if(!(value instanceof Array)){
                var temp = value;
                value = [];
                if(temp){
                    value[value.length] = temp;
                }
            }
            value[value.length] = key+"="+escape(val);
        }
        this.setExpires = function(date){ expires=date; }
        this.getExpires = function(){ return expires; }
        this.setDomain = function(sD){ domain=sD; }
        this.getDomain = function(){ return domain; }
        this.setSecure = function(scr){ secure = !!scr; }
        this.getSecure = function(){ return secure; }
        this.save = function(){
            if(name  && value){
                if(value instanceof Array){
                    // if the value is as array, we join the array
                    value=value.join("&");
                }
                document.cookie = name+'='+escape( value ) +
                    ( ( expires ) ? ';expires='+expires.toGMTString() : '' ) + //expires.toGMTString()
                    ( ( path ) ? ';path=' + path : '' ) +
                    ( ( domain ) ? ';domain=' + domain : '' ) +
                    ( ( secure ) ? ';secure' : '' );
            }
        }
        this.remove = function(){
            // The cookie removed if the expires date is before today
            expires = new Date(new Date().getTime()-1000*60*60*24);
            this.save();
        }
    };

    Cookie.get = function(name){
        /*
            the document.cookie return a string contains all the cookies available in the browser for the specific domain in format of: Name=Value;Name=Value;Name=Value
            this function take only the cookie with the requested name and return a Cookie object with it's value.
            if there isn't a cookie with the requested name, the function returns an empty cookie object with the requested name
        */
        var start = document.cookie.indexOf( name + "=" );
        var len = start + name.length + 1;
        var cookie = new Cookie();
        if ( !((( !start ) && ( name != document.cookie.substring( 0, name.length ) )) || (start==-1) ) ) {
            var end = document.cookie.indexOf( ';', len );
            if ( end == -1 ) end = document.cookie.length;
            cookie.setValue(unescape( document.cookie.substring( len, end ) ));
        }

        cookie.setName(name);
        return cookie;
    }
   


function toggleListCompare(visible) {
  element = document.getElementById('listCompare');
   	if (element.firstChild) {
		element.removeChild(element.firstChild);
	}
	if (visible) {
		element.innerHTML=bottomCompareLink;
	} else {
		element.innerHTML='&nbsp;';
	}	
}


function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}


function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function toggleCompareCheckmark(pid) {
	var allcookies = document.cookie;
	var pos = allcookies.indexOf("comparison=");
	var value = '';
	var countValues = 0;
	var compareArray = new Array();
	
	if (pos != -1) {
		var start= pos + 11;
		var end = allcookies.indexOf(";", start);
		if (end == -1) end  = allcookies.length;
		value = allcookies.substring(start, end);
		value = unescape(value);
		compareArray = value.split(',');
	}
	
	var productID = pid.match(/\d+/);
	if ( compareArray.length > 0) {
		var compareList = compareArray.toString();
	} else {
		var compareList = '';
	}
	
	//alert('array length=' + compareArray.length + ' productID='+productID + ' List=' + compareList);
	
	/* Remove product id from array if it exsists */
	if ( compareArray.length == 0) {
		movepic(pid,'images/da/list/bn_compare_checked.gif');
		compareList = productID;
	} else {
		if ( compareList.match(productID) ) {
			movepic(pid,'images/da/list/bn_compare_notchecked.gif');
			compareList = compareList.replace(productID,'');
			compareList = compareList.replace(',,',',');
			if (compareList == ',') {
				compareList='';
			}
		} else {
			if (compareArray.length >= 5) {
				alert (varCompareError);
				//alert ('Der kan kun sammenlign');
				return;
			} else {
				movepic(pid,'images/da/list/bn_compare_checked.gif');
				if (productID>0) {
					compareList = compareList + "," + productID;
					
				}
			}
		}
	}
	
//	alert ('Toggle:' + productID + " result=(" + compareList+")");

	document.cookie = "comparison=" + compareList + ";";
	
	var compareElement = document.getElementById('compare');
	
	if (compareElement != null) {
		//alert('in compare list');
		if (compareList.length>0) {
			showCompare();
		}
	} else {
		if (typeof(toggleCompareLinks)=='function') {
			if ( compareList.length>0) {
				toggleCompareLinks(true);
			} else {
				toggleCompareLinks(false);
			}	
		}
	}
	return;
}



var showCompare = function(sortid) {
	toggleAnimation(true);
	toggleCompareLinks(false);
	ajax.doGet('/partCompare.php?sortid='+sortid,updateList);
	return(false);
}
 

var removeProduct = function(pid) {
//	alert('in removeProduct'+pid);
	toggleCompareCheckmark(pid);
}


var showList = function(productid,catid) {
	toggleAnimation(true);
	ajax.doGet('/partList.php?productid=' + productid + '&catid=' + catid, updateList);
	return(false);
}


var openInvoice = function (url) {
	window.open(url, 'Info','menubar=1,width=430,height=600,toolbar=1,scrollbars=1,resizable=1');
	return(false);
}


var openSubPage = function (url) {
	window.open(url, 'Info','menubar=1,width=430,height=600,toolbar=1,scrollbars=1,resizable=1');
	//return(false);
}

var openDetailPage = function(url,winName) {
	if (typeof winName == "undefined") {
		winName='Detail';
	}
	window.open(url,winName,'menubar=0,resizeable=1,,width=450,height=650,toolbar=0,scrollbars=1'); 
	return(false);
}


var validatePercentage = function(elementId,value,warningId) {
	var err=0;
	if (value == '') {
		//alert('empty');
		err = err + 1;
	}
	if (value < 0) {
		//alert(elementId + 'less than 0');
		err = err + 1;
	}
	if (value > 100) {
		//alert('greater than 100');
		err = err + 1;
	}
	if ( err == 0) {
		element = document.getElementById(warningId);
		if (element.firstChild) {
			element.removeChild(element.firstChild);
		}
		element.innerHTML='';
		return true;
	} else {
		element = document.getElementById(warningId);
		if (element.firstChild) {
			element.removeChild(element.firstChild);
		}
		element.innerHTML=varFilterError;
		return false;		
	}
}


var validateAllPercentage = function (theForm) {
	var elementCount = theForm.elements.length;
	var errs = 0;
	var i=0;

	for ( i=0 ; i<elementCount; i++) {
		elementID = theForm.elements[i].id;
		elementValue = theForm.elements[i].value;
		if ( elementID.match("input_")) {
			elementLocalNumber = elementID.slice("input_".length);
			elementWarning = 'warnid_'+elementLocalNumber;
			if (validatePercentage(element,elementValue,elementWarning)) {
				/* Nothin really, as there are no warnings */
			} else {
				errs = errs + 1;
			}
		}
	}
	if (errs > 0) {
		//alert('errs in form='+errs);
		return false;
	} else {
		return true;
	}
	
}

function nothing(data){
	alert('Nothing is done'+data);
}


