// DIV PAGEFUNCTIONS
function ncms_getPageSize() {
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) { 
    xScroll = document.body.scrollWidth;
    yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
    } else if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
    xScroll = document.documentElement.scrollWidth;
    yScroll = document.documentElement.scrollHeight;
    } else { // Explorer Mac...would also work in Mozilla and Safari
    xScroll = document.body.offsetWidth;
    yScroll = document.body.offsetHeight;
    }
    
    var windowWidth, windowHeight;
    if (self.innerHeight) { // all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
    } 
    
    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
    pageHeight = windowHeight;
    } else { 
    pageHeight = yScroll;
    }
    
    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){ 
    pageWidth = windowWidth;
    } else {
    pageWidth = xScroll;
    }
    
    
    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
    return arrayPageSize;
}

function ncms_getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {     // Explorer 6 Strict
        yScroll = document.documentElement.scrollTop;
        xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
        xScroll = document.body.scrollLeft;    
    }
    arrayPageScroll = new Array(xScroll,yScroll);
    return arrayPageScroll;
}

function getQuerystringKey(key) { // optionally pass a querystring to parse
    qs = null//alert(key)
    if (qs == null)
        qs=window.location.search.substring(1,window.location.search.length);
    if (qs.length == 0) return "";
    
// Turn <plus> back to <space>
    qs = qs.replace(/\+/g, ' ')
    var args = qs.split('&') // parse out name/value pairs separated via &
// split out each name=value pair
    for (var i=0;i<args.length;i++) {
        var value;
        var pair = args[i].split('=')
        var name = unescape(pair[0])

        if (pair.length == 2)
            value = unescape(pair[1])
        else
            value=""
        if (name==key)
         return value
    }
    return ""
}

//CONTENT
function goToUrl(tUrl){
    document.location.href=tUrl;
}
function contactLagerShopClose(){
	$('#stockContacForm').fadeOut();
}
function contactLagerIsDone(messageStr){
	alert(messageStr)
	$('#stockContacForm').fadeOut();
	document.stocksaleForm.recipient.value=''
	document.stocksaleForm.message.value=''
	document.getElementById("stocksaleShopname").innerHTML=''
}

function contactLagerShop(obj,butiknavn,butikemail,butikvare){
    // Calculate top and left offset for the jquery-lightbox div object and show it
	document.stocksaleForm.recipient.value=butikemail
	document.stocksaleForm.message.value=butikvare
	document.getElementById("stocksaleShopname").innerHTML=butiknavn
	
    $('#stockContacForm').css({
        top:    $(obj).offset().top-200,
        left:   $(obj).offset().left-400
    }).fadeIn();
	//alert()
//	$('stockContacForm')
}
function getLagerSalg(){
	shop=''; lagerSelect=''
   //shop=document.shopSel.shopID.options[document.shopSel.shopID.selectedIndex].value
	try{
	  shop=document.shopSel.shopID.options[document.shopSel.shopID.selectedIndex].value;
	  vfamSelect=document.prodSel.vfamSelect.options[document.prodSel.vfamSelect.selectedIndex].value;
	  vuklasSelect=document.prodSel.vuklasSelect.options[document.prodSel.vuklasSelect.selectedIndex].value;
	  prodnameSelect=document.prodSel.prodnameSelect.options[document.prodSel.prodnameSelect.selectedIndex].value;
	  qry='?shopID='+shop+'&vfamSelect='+escape(vfamSelect)+'&vuklasSelect='+vuklasSelect+'&prodnameSelect='+prodnameSelect;
	  lagerSelect="true"
	  alert(shop)
	}catch(e){
	  qry='?shopID='+getQuerystringKey('activeShop')
	}
	if(lagerSelect=='' && !isNaN(arguments[0])){
		qry='?shopID='+arguments[0]	
	};
	qry+= qry=='' ? "?nocahce="+Math.random() : "&nocahce="+Math.random()
  
   //shop=document.prodSel.vfamSelect.options[document.prodSel.vfamSelect.selectedIndex].value
   var html = $.ajax({
   url: "/data/lagersalg.asp"+qry,
   async: false
   }).responseText;
  //alert(html)
   document.getElementById("stocksale").innerHTML=html
   $('#stockContacForm').corner("3px");
}

function showProdnames(){
	getLagerSalg()//alert(prodName)
}

function getProductTests(){
	qry=''
	try{
	   pageSelect=document.prodtestSel.pageID.options[document.prodtestSel.pageID.selectedIndex].value
	   vfamSelect=document.prodtestSel.brand.options[document.prodtestSel.brand.selectedIndex].value
	   qry='?pID='+pageSelect+'&vfam='+escape(vfamSelect)
	   }catch(e){qry=''}
	   qry+= qry=='' ? "?nocahce="+Math.random() : "&nocahce="+Math.random()
	   var html = $.ajax({
	   url: "/data/productTest.asp"+qry,
	   async: false
	   }).responseText;
	  document.getElementById("productTestList").innerHTML=html
}


// TOP SØGE FELT 
/*var isTopSearching=false
function showTopSearchResult(){
    topsearchKeyword=document.getElementById("topsearchTxt").value
    if(topsearchKeyword.length>2){
        if(isTopSearching==false){
            document.getElementById("topSearchresultDiv").style.display="block"
            document.getElementById("topsearching").style.background="URL(/files/site/images/searchtop_on.gif)"
            isTopSearching=true
        }
		setTimeout('getTopSearchResult()',500)
    }else{
        closeSearchResult()
    }
}
function closeSearchResult(){
    if(isTopSearching==true){
        document.getElementById("topSearchresultDiv").style.display="none"
        document.getElementById("topsearching").style.background="#FFFFFF"
        isTopSearching=false
    }
}
function getTopSearchResult(){
	topsearchKeyword=document.getElementById("topsearchTxt").value
    if(isTopSearching==true){
        $.get("/data/topsearch.asp?q="+topsearchKeyword, function(data){//alert("Data Loaded: " + data);
          document.getElementById("topSearchresult").innerHTML=data        
        });
    }
}*/
function closeSearchResult(objName){
	document.getElementById("topSearchresultDiv").style.display="none"
	document.getElementById("topsearching").style.background="#FFFFFF"
}
function showTopSearchResult(){
	topsearchKeyword=document.getElementById("topsearchTxt").value
	if((topsearchKeyword=="")||(topsearchKeyword.length<3)){
		DoCloseSearchResult("topSearchresultDiv");return;
	}
	strURL="/data/topsearch.asp?q="+topsearchKeyword
	//alert(strURL)
	var req = GetXmlHttpObject();
	if (req){
		req.onreadystatechange = function() {
			if ((req.readyState==4 || req.readyState=="complete")){ //når data er returneret
				//alert(req.responseText)
				document.getElementById("topSearchresultDiv").style.display="block"
				document.getElementById("topsearching").style.background="URL(/files/site/images/searchtop_on.gif)"
				document.getElementById("topSearchresult").innerHTML=req.responseText
				req=null
			}
		}
		req.open("GET", strURL, true);
		req.send(null);
	}
}
function closeAfterOneSecound(){
    setTimeout('closeSearchResult("topSearchresultDiv")',1000);
}
function showHideDiv(obj){
    if(document.getElementById(obj).style.display==""){
        document.getElementById(obj).style.display="none"
    }else{
        document.getElementById(obj).style.display=""
    }
}

function showBigImageDetail(){
    imgSrc=document.getElementById("detailImage").src
    imgSrc=imgSrc.replace("_b.jpg","_m.jpg")
    imgSrc='<a href=# onClick="showHideDiv(\'bigImageDetail\');"><img src="'+imgSrc+'" alt="" border="0"></a>'
    document.getElementById("bigImageDetail").innerHTML=imgSrc
    document.getElementById("bigImageDetail").style.display=""
}

function submitThisForm(fName){
    document[fName].submit();
}

function showDetailImage(imgStr){
    try{
        document.getElementById("detailImageContainer").img.src=imgStr.replace('_b.jpg','_m.jpg')
    }
    catch(imgStr){}
}

function hideBuyContainer(tURL) {
    //$('#basketDetailContainer').remove();
     document.getElementById("basketDetailContainer").innerHTML='<div id="basket-loading-gif"><p></p></div>'
    //$('#intoBasketContainer').fadeOut(function() { $('#intoBasketContainer').remove(); });
    // Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
    //$('embed, object, select').css({ 'visibility' : 'visible' });
    $('#intoBasketContainer,#basketDetailContainer').unbind("click")//alert(tURL)
    if(tURL!=''){
        document.location.href=tURL
    }else{
        document.location.reload()
    }
    
    return false;
}
function showBuyContainer(pformName){
    
    var icbdiv=document.createElement("div");
    icbdiv.setAttribute('id', "intoBasketContainer");
    document.body.appendChild(icbdiv)
    //$('body').append('<div id="intoBasketContainer"></div><div id="basketDetailContainer"></div></div>'); 
    $('embed, object, select').css({ 'visibility' : 'hidden' });
     var arrPageSizes = ncms_getPageSize()
    $('#intoBasketContainer').css({
        backgroundColor: "#000", 
        opacity: 0.8, 
        width: arrPageSizes[0], 
        height: arrPageSizes[1]
    }).fadeIn();
    
    var bdcdiv=document.createElement("div");
    bdcdiv.setAttribute('id', "basketDetailContainer");
    document.body.appendChild(bdcdiv)

    var arrPageScroll = ncms_getPageScroll();
    // Calculate top and left offset for the jquery-lightbox div object and show it
    $('#basketDetailContainer').css({
        top:    arrPageScroll[1] + (arrPageSizes[3] / 10),
        opacity: 1
        //,left:   arrPageScroll[0]
    }).show();
    // Assigning click events in elements to close overlay
    $('#intoBasketContainer,#basketDetailContainer').click(function() {
        hideBuyContainer('');  return false;                                    
    });

    updateByContainer(pformName)

    return false;
    //showHideDiv(iVal)
}

function updateByContainer(pformName)    {
   myform=document.forms[pformName]
   var inputs = [];
  $(':input', myform).each(function() {
    inputs.push(this.name + '=' + escape(this.value));
  })
  //alert(inputs.join('&'))
  // now if I join our inputs using '&' we'll have a query string
  jQuery.ajax({
    data: inputs.join('&'),
    url: myform.action,
    timeout: 2000,
    error: function(xhr, status, error) {
        // Display a generic error for now.
    	alert(xhr.responseText);  
		return false;
    },
	//error: function() {
    //console.log("Failed to submit");
    // alert('Failed')
    //document.getElementById("basketDetailContainer").innerHTML=inputs.join('&')
    //  return false;
    //},
    success: function(r){
      //alert(r)
      //$("#basketDetailContainer").html=r;
      document.getElementById("basketDetailContainer").innerHTML=r
      return false;
    }
  })
  return false;
    
}

function checkUserlogin(){
    myform=document.userloginform
    if((myform.userName.value=="")||(myform.userPwd.value=="")){
        alert("Udfyld venligst begge felter"); return false    
    }else{
         submitThisForm("userloginform"); return false    
    }
    
}

function checkLookupUserForm(){
    myform=document.lookupUserForm
    if((myform.chkEmail.value!="")||(myform.chkPhoneNumber.value!="")){
        return true
    }else{
        alert("Udfyld venligst begge felter"); 
        return false;
    }
}

function confirmUserDelete(){
	try{
		return confirm('Er du sikker på at du ønsker å avslutte medlemsskapet i Kundeklubben?')
	}catch(e){
		return false
	}
}

// EVENTFUNCTIONER //////////////////
function showEvent(eid){
  showContainer= eid=="" ? "" : "none" 
	document.getElementById("eventMaincontent").style.display=showContainer;
	document.getElementById("eventRightcontent").style.display=showContainer;
	//    
	var html = $.ajax({
	  url: "/data/events/getEvents.asp?activeEvent="+eid+"&nocache="+Math.random(),
	  async: false
	 }).responseText;
	//alert(html)
	document.getElementById("eventPageContent").innerHTML=html
	Cufon.replace('#eventPageContent h1');
}
function subscribeEvent(iEventID){
   url="/data/events/eventSave.asp?cid=2&eventID="+iEventID;
   win="eventSubscribe";
   feature="width=490,height=340";
   window.open(url,win,feature);
   return false;
}
function unSubscribeEvent(iEventID){
   url="/data/events/eventDel.asp?cid=2&eventID="+iEventID;
   win="eventUnSubscribe";
   feature="width=490,height=340";
   window.open(url,win,feature);
   return false;
}

function compareProducts(pageID){
	var result = "";			
	$("input[type=checkbox]").each( function () {
			 if(this.checked==true){
					result=result + this.value + ",";
			 }
	});
	if(result.length>4)
		window.open('/config/compare.asp?pageID='+pageID+'&cp='+result,'','width=500,height=400,resizable=1,scrollbars=1');
	return false;


}
/// FUNKTION TIL RUND HJØRNER PÅ INPUT /////
function roundInput(input_obj){
    //alert('corner')
    var input = input_obj;
    var input_width = input_obj.css("width"); //get the width of input
    //alert(input_width)
    var wrap_width = parseInt(input_width) + 12; //add 10 for padding
    var wrap_class = input_obj.attr("className")+''
    //alert(input.name+' '+wrap_class)
    wrap_class=wrap_class.match(/rounded_[a-z]{3,5}/)
    //alert(wrap_class)
    //var wrap_background=input.parent().css('background')
    wrapper = input.wrap("<div class='roundedInputWhite'></div>").parent();
    wrapper.wrap("<div class='"+wrap_class+"_border' style='width: "+wrap_width+"px;'></div>"); //apply border
    wrapper.corner("round 3px").parent().css('padding', '1px').corner("round 3px"); //round box and border
}

function roundInputSubmit(input_obj){
    //alert('corner')
    var input = input_obj;
    var input_width = input_obj.css("width"); //get the width of input
    //alert(input_width)
    var wrap_width = parseInt(input_width) + 12; //add 10 for padding
    var wrap_class = input_obj.attr("className")+''
    //alert(input.name+' '+wrap_class) //wrap_class=wrap_class.match(/rounded_[a-z]{3,5}/) //alert(wrap_class) //var wrap_background=input.parent().css('background')
    wrapper = input.wrap("<div class='"+wrap_class+"' style='width: "+wrap_width+"px;padding:1px'></div>").parent();
    //wrapper.wrap("<div class='"+wrap_class+"_border' style='width: "+wrap_width+"px;'></div>"); //apply border
    wrapper.corner("round 3px").parent().css('padding', '1px').corner("round 3px"); //round box and border
}

$(document).ready(
    function() {
    $("input[type=text]").each(function(){
    roundInput($(this));
    });
	 $("input[type=password]").each(function(){
    roundInput($(this));
    });
	$("input[type=submit]").each(function(){
    roundInputSubmit($(this));
    });
    $("textarea").each(function(){
    roundInput($(this));
    });
});
///////////////////////////////////////////////
