//ONLOAD
window.onload = function () {
    //display errors!
    //alert("Wiseled testing.. sorry for inconw...");
    $(document).ready(function () {
        if (getQueryVariable("msg") != "" && getQueryVariable("fromLogin") != "") {
            //alert("Testing onload again");
            //displayError(getQueryVariable("msg"));

            if (isdefined('CollapsiblePanel1')) {
                CollapsiblePanel1.open();
                var td = $("<td></td>").text(getQueryVariable("msg")).addClass("orangeTxt");
                $("<tr><td> </td></tr>").append(td).insertBefore($("#form1 > table > tbody > tr:last"));
            }
        }
        else if (getQueryVariable("msg") != "") {
            $("#statusMessage > td:last").text(unescape(getQueryVariable("msg"))).show();
            $("#statusMessage > td:first").show();
            $("#statusMessage").show();
        }

        try {
            $(".formJQValidate").validate();
            if (jQuery.livequery != 'undefined') {
                $("label.error").livequery(function () {
                    //$(this).css("color", "red").css("float", "right");
                    $(this).css({ "color": "#FF8000", "float": "right", "font-weight": "bold" });
                });
            };

            if (getQueryVariable("reg_confirm_redirect") && getQueryVariable("reg_confirm_redirect") == "1") {
                window.location = "cRegConfirmation.htm";
            }
			
			
			
			
			
        } 
        catch (e) {
        }
		///author pj
	  try {
            $("#sigupNewsForm").validate({
   errorLabelContainer: $('div.success').fadeIn().css({ "color": "#FF8000", "float": "left", "font-weight": "bold" })
  
})

        } 
        catch (e) { }
		
		   try {
       		 $("form#sigupNewsForm").submit(function() {  
			// we want to store the values from the form input box, then send via ajax below  
		
			var email     = $('#email').attr('value');
			var include_link = "";
            include_link = "http://www.wisedive.com/AJAX/signup_newsletter.php";
				$.ajax({  
					type: "POST",  
					url: include_link, 
					dataType : 'json', 
					data: "email="+email,  
				    success: function(j){  
								if(j.error)
						{
							$('div.success').fadeIn().html(j.msg).css({ "color": "#FF8000", "float": "left", "font-weight": "bold" });
						}
						else
						{ 
							$('form#submit').hide(function(){$('div.success').fadeIn().html(j.msg);}).css({ "color": "#FF8000", "float": "left", "font-weight": "bold" });
						}  
					}
           });  
       return false;  
});  
  } 
        catch (e) {
        }
 //end pj
		
        // Printing the Logged is AS XXXX-Fake-user line on top of page.

        try {
            //alert("Wiseled testing");
            var include_link = "";
            include_link = "http://www.wisedive.com/AJAX/admin_fake_login_check.php";
            $.ajax({
                url: include_link,
                cache: false,
                success: function (html) {
                    if ($("#container")) {
                        if (html.replace(/\s/g, "") != "") {
                            $("#container").prepend(html);
                        }
                    }
                }
            });
        } catch (err) { }
        // End of print logged in AS XXXX-Fake-user

        // USED ON aShowWiseDealers (Same funtionality as on admin/Show_dealer
        try {
            $("#treetable tr.cust_id").tooltip(
			{
			    tip: '#tooltip',
			    cancelDefault: true,
			    relative: true,
			    offset: [5, 15],
			    laze: true,
			    delay: 0,
			    predelay: 300,
			    onBeforeShow: function () {
			        var tr = this.getTrigger();
			        while (!tr.is("tr.cust_id")) tr = tr.parent();
			        //alert(this.getTrigger().data("title"));

			        $("#tooltip").html('');

			        $.get("/AJAX/getCustDiscountPurchaseInfoWithDate.php", { cust_id: tr.data("title"), dealer_id: tr.attr("rel") },
					function (data) {
					    $("#tooltip").html(data);
					});
			    }
			});
        } catch (e) { }
        // End of aShowWiseDealers needed JS
    });
}

function isdefined(variable) {
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function resendWelcomeMsg() {
    send_to = document.getElementById("cellphone").value;
	
	if (send_to == "") {
		return false;
	}

	if (send_to.substring(0,1) != "+"){
		alert("Numbers should start with countrycode. E.g. +45");
		return false;
	}
	
	if (!IsNumeric(send_to.substring(1))){
		alert("Not a vaild number!");
		return false;
	}
	
	send_to = send_to.replace('+', 'X');
	//alert("sender til: " + send_to);
	//alert("VIRK NU!!!" + send_to);	
	var currentTime = new Date();
        
    var include_link = "";
    include_link = "http://www.wisedive.com/AJAX/b_sendwelcomeSMS.php?to=" + send_to + "&nocache=" + currentTime;
    $.ajax({
        url: include_link,
        cache: false,
        success: function(html) {
            if (ltrim(html) == "") {
                alert("SMS sent!")  ;
            }
            else {
                alert(ltrim(html));
            }
		}
    });
    
    return false;
}

function get_user_logged_in(){
    // Printing the Logged is AS XXXX-Fake-user line on top of page.
    var include_link = "";
    include_link = "http://www.wisedive.com/AJAX/admin_fake_login_check.php";
    $.ajax({
        url: include_link,
        cache: false,
        success: function(html){
            if($("#container")) {
                $("#container").prepend(html);
            }
        }
    });
    // End of print logged in AS XXXX-Fake-user	
}

function getQueryVariable( name ){  
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
	var regexS = "[\\?&]"+name+"=([^&#]*)";  var regex = new RegExp( regexS );  var results = regex.exec( window.location.href );  if( results == null )    return "";  else    
	return decode(results[1]);
}

/* aShowWiseDealers BEGIN */
function toggle_purchased_products(id){
	if( $("#"+id) ){
		$("#"+id).toggle();	
	}
}
/* aShowWiseDealers END */

function showstats(year){
	//alert("change to: " + year);	
	$.ajax({
	    url: "/AJAX/showstats.php?year="+year,
  		cache: false,
  		success: function(html) {
			$("#div_stats").html(html);
  		}
	});
}

function setCanChangeWiseDealers() {
	if(document.getElementById("reg_dealer").style.display == "none") {
		document.getElementById("reg_dealer").style.display = "";
		
		if(document.getElementById("canregisterdealers").checked == true) {
			document.getElementById("canregisterdealers").checked = false;
		}
		document.getElementById("show_blog").style.display ="none";
	
		document.getElementById("blog_box").style.display ="none";
		document.getElementById("reg_company").innerHTML = "Company*";
		jscss('add', document.getElementById("company"), 'required', '');

    } 
    else {
		document.getElementById("reg_dealer").style.display = "none";
			document.getElementById("show_blog").style.display ="block";
			
		document.getElementById("blog_box").style.display ="block";
		
		document.getElementById("reg_company").innerHTML = "Company";
		jscss('remove', document.getElementById("company"), 'required', '');
	}
}

function cart_hide_zipcode_error() {
	var elm = document.getElementById("cart_error_zipcode");
	if(elm) {
		if(document.getElementById("cart_error_zipcode").style.display == "none"){
			return true;
        } 
        else {
			document.getElementById("cart_error_zipcode").style.display = "none";
			return true;
		}
	}
	return true;
}

function jscss(a,o,c1,c2) {
    switch (a) {
        case 'swap':
            o.className=!jscss('check',o,c1)?o.className.replace(c2,c1): o.className.replace(c1,c2);
            break;
        case 'add':
            if (!jscss('check', o, c1)) {
                o.className += o.className ? ' ' + c1 : c1;
            }
            break;
        case 'remove':
            var rep=o.className.match(' '+c1)?' '+c1:c1;
            o.className=o.className.replace(rep,'');
            break;
        case 'check':
            return new RegExp('\\b'+c1+'\\b').test(o.className)
            break;
    }
}


function setStateDropDown(country) {
	// $.post("AJAX/cart02_state_dropdown.php", { state: oldvalue });
	//var oldvalue = document.submit_a_customer.stateprovince.value;
	var oldvalue = document.getElementById("stateprovince").value;
	//var drpdown = $.post("AJAX/cart02_state_dropdown.php", { state: oldvalue });

	if (country == 'US' || country == 'CA') {
		$.ajax({
			success: function(html) {
				$("#state_asterics").html("*");
				//$("#state_field").html("<input type='text' class='required' id='stateprovince' name='stateprovince' value='" + oldvalue + "' size='40' />");
				//$("#state_field").html( drpdown );
			
				$.ajax({
				    url: "/AJAX/cart02_state_dropdown.php?state=" + escape(oldvalue),
  				    cache: false,
				    success: function(html){
					    //$("#dealerCountrySelect").html(html);
					    //displayError(html);
					    $("#state_field").html( html );
				    }
			    });
            }
        });
    }
	else {
		$.ajax({
  			success: function(html) {
    			$("#state_asterics").html("");
				//$("#state_field").html("<input type='text' id='stateprovince' name='stateprovince' value='" + oldvalue + "' size='40' />");
				$("#state_field").html("<input type='text' id='stateprovince' name='stateprovince' value='' size='40' />");
  			}
		});
	}
}

//function aRegisterSeller_add_product(parent,dealerid){
function aRegisterSeller_add_product(parent, dealerid){
	$.ajax({
  		//url: "AJAX/addproducttodicountlist.php?prod_id=" + escape(document.getElementById("products").value) + "&parent=" + escape(parent),
		url: "/AJAX/addproducttodicountlist.php?prod_id=" + escape(document.getElementById("products").value) + "&parent=" + escape(parent) + "&id=" + escape(dealerid),
  		cache: false,
  		success: function(html) {
    		//$("#dealerCountrySelect").html(html);
			//displayError(html);
			$("#discounttree").html(html);
            $("#frm_a_register_seller").submit();
  		}
	});
}
//pj 
function aRegisterSeller_add_products(parent, dealerid) {
    $.ajax({
        //url: "AJAX/addproducttodicountlist.php?prod_id=" + escape(document.getElementById("products").value) + "&parent=" + escape(parent),
        url: "AJAX/addproducttodicountlist.php?prod_id=" + escape($('input:checked[name=products]').map(function () { return $(this).val(); }).get().join(",")) + "&parent=" + escape(parent) + "&id=" + escape(dealerid) + "&check=true",
        cache: false,
        success: function (html) {
            //$("#dealerCountrySelect").html(html);
            //displayError(html);
            $("#discounttree").html(html);
            $("#frm_a_register_seller").submit();
        }
    });
}

//function aRegisterSeller_delete_product(disc_id){
function aRegisterSeller_delete_product(disc_id, dealerid) {
	$.ajax({
		url: "/AJAX/deletefromdiscountlist.php?prod_group_id=" + escape(disc_id) + "&id=" + escape(dealerid),
  		cache: false,
  		success: function(html) {
    		//$("#dealerCountrySelect").html(html);
			//displayError(html);
            
            // This aparently adds an extra row set of Tactical and Compact Flashlight
            // All things are saved correctly, so a page refresh display everything as it should.
			//$("#discounttree").html(html);
            $("#frm_a_register_seller").submit();
  		}
	});
}

function bsChangePersonalInfo_SavePersonalInfo() {
	// This function is no more in use as of December 2nd 2009 (11:50) 
	
	var updateUrl = "";
	var dropdownIndex = document.getElementById("countrycodes").selectedIndex;
	var dropdownValue = document.getElementById("countrycodes")[dropdownIndex].value;

	updateUrl = "AJAX/customer_update_personal_info.php?";
	updateUrl += "firstname=" + escape(document.getElementById("firstname").value);
	updateUrl += "&lastname=" + escape(document.getElementById("lastname").value);
	updateUrl += "&title=" + escape(document.getElementById("title").value);
	updateUrl += "&address1=" + escape(document.getElementById("address1").value);
	updateUrl += "&address2=" + escape(document.getElementById("address2").value);
	updateUrl += "&address3=" + escape(document.getElementById("address3").value);
	updateUrl += "&zipcode=" + escape(document.getElementById("zipcode").value);
	updateUrl += "&city=" + escape(document.getElementById("city").value);
	updateUrl += "&stateprovince=" + escape(document.getElementById("stateprovince").value);
	updateUrl += "&countrycodes=" + document.getElementById("countrycodes")[dropdownIndex].value;
	updateUrl += "&phone=" + escape(document.getElementById("phone").value);
	updateUrl += "&email=" + escape(document.getElementById("email").value);
	updateUrl += "&cellphone=" + escape(document.getElementById("cellphone").value);

	$.ajax({
		url: updateUrl,
		cache: false,
  		success: function(html) {
			displayError(html);
  		}
	});
}


function bsWriteNewPost_SavePost() {
	// This function is no more in use as of December 2nd 2009 (11:50) 
	var updateUrl = "";
	updateUrl = "/AJAX/bsWriteNewPost_SavePost.php?";
	updateUrl += "title=" + escape(document.getElementById("title").value);
	updateUrl += "&content=" + escape(document.getElementById("content").value);
	$.ajax({
		url: updateUrl,
		cache: false,
  		success: function(html) {
    		//$("#dealerCountrySelect").html(html);
			displayError(html);
  		}
	});
}



function bsManageBlog_SaveBlogInfo() {
	var updateUrl = "";
	updateUrl += "/AJAX/bsManageBlog_SaveBlogInfo.php?";
	updateUrl += "blogname=" + escape(document.getElementById("blogname").value);
	$.ajax({
		url: updateUrl,
		cache: false,
  		success: function(html) {
  			//alert(html);
  			$("#blogmessage > td:last").text(html).show();		// id was name before
			$("#blogmessage > td:first").show();			// id was name before
			$("#blogmessage").show();				// id was name before
    		//$("#dealerCountrySelect").html(html);
			//displayError(html);
  		}
	});
}

function bsManageBlog_SaveBlogInfo_withImage() {
	var updateUrl = "";
	updateUrl += "/AJAX/bsManageBlog_SaveBlogInfo.php?";
	updateUrl += "blogname=" + escape(document.getElementById("blogname").value);
	$.ajax({
		url: updateUrl,
		cache: false,
  		success: function(html) {
  			
			$("#blogmessage > td:last").text(html).show();		
			$("#blogmessage > td:first").show();			
			$("#blogmessage").show();	
			// Submit the form with image-info/href to upload/save the picture.
			$("#frm_upload_top_image").submit();
			
			/*
  			$(".statusMessage[id='blogMessage'] > td").text(html);
			$(".statusMessage[id='blogMessage'] > td").show();
			$(".statusMessage[id='blogMessage']").show();
			*/
			
			
			//displayError(html);
  		}
	});
}

function bsManageBlog_SaveAboutYouInfo_AndSubmitImage() {
	bsManageBlog_SaveAboutYouInfo();
	document.frm_upload_profile_image.submit();
}

function bsManageBlog_SaveAboutYouInfo() {
	//alert('Wiseled testing: about you info being saved');	
	var updateUrl = "";
	updateUrl = "/AJAX/bsManageBlog_SaveAboutYouInfo.php?";
	updateUrl += "aboutyouname=" + escape(document.getElementById("aboutyouname").value);
	updateUrl += "&occupation=" + escape(document.getElementById("occupation").value);
	updateUrl += "&aboutyoutext=" + escape(document.getElementById("aboutyoutext").value);
	//updateUrl += "&customer=" + escape(document.getElementById("current_customer").value);
	//test = "Wiseled testing: " + updateUrl;
	
	//alert(test);
	
	var tsTimeStamp= new Date().getTime();
	//alert( "Wisled testing: " + updateUrl);
	$.ajax({
		url: updateUrl,
		cache: false,
		time: tsTimeStamp,
  		success: function(html) {
			//alert("Wiseled testing: Saving succeeded");
			//displayError(html);
			//alert(html);
			
			$("#aboutyoumessage > td:last").text(html).show();
			$("#aboutyoumessage > td:first").show();
			$("#aboutyoumessage").show();
  		}
	});
}

function bsManageBlog_SaveAboutYouInfo_withImage() {
	//alert('Wiseled testing: about you info being saved');	
	var updateUrl = "";
	updateUrl = "/AJAX/bsManageBlog_SaveAboutYouInfo.php?";
	updateUrl += "aboutyouname=" + escape(document.getElementById("aboutyouname").value);
	updateUrl += "&occupation=" + escape(document.getElementById("occupation").value);
	updateUrl += "&aboutyoutext=" + escape(document.getElementById("aboutyoutext").value);
	//updateUrl += "&customer=" + escape(document.getElementById("current_customer").value);
	//test = "Wiseled testing: " + updateUrl;
	//alert(test);
	
	var tsTimeStamp= new Date().getTime();
	//alert( "Wisled testing: " + updateUrl);
	$.ajax({
		url: updateUrl,
		cache: false,
		time: tsTimeStamp,
  		success: function(html) {
			//alert("Wiseled testing: Saving succeeded");
			//displayError(html);
			//alert(html);
			//alert("Wiseled Testing: " + html);
			
			//$(".statusMessage[id='aboutYouMessage'] > td").text(html);
			//$(".statusMessage[id='aboutYouMessage'] > td").show();
			//$(".statusMessage[id='aboutYouMessage']").show();
			
			$("#aboutyoumessage > td:last").text(html).show();
			$("#aboutyoumessage > td:first").show();
			$("#aboutyoumessage").show();
						
			//alert('Wiseled testing: ..start to save Image');
			$("#frm_upload_profile_image").submit();
  		}
	});

}

function testAlert(message) {
	alert(message);	
}

function validateSMSFields2() {
	var validFields = true;
	
	if( document.getElementById("txtfriend1") ) {
		if( validatecellphonewitherror(document.getElementById("txtfriend1"), 'cellphone_label_1')) {
		} 
        else {
			//alert("false 1");
			//return false; 
			validFields = false;
		}
	}
	if( document.getElementById("txtfriend2") ) {
		if( validatecellphonewitherror(document.getElementById("txtfriend2"), 'cellphone_label_2')) {
		} 
        else {
			//alert("false 2");
			//return false; 
			validFields = false;
		}
	}
	if( document.getElementById("txtfriend3") ) {
		if( validatecellphonewitherror(document.getElementById("txtfriend3"), 'cellphone_label_3')) {
		} 
        else { 
			//alert("false 3");
			//return false; 
			validFields = false;
			} 
	}
	if ( document.getElementById("txtfriend4") ) {
		if( validatecellphonewitherror(document.getElementById("txtfriend4"), 'cellphone_label_4')) {
		} 
        else { 
			//alert("false 4");
			//return false; 
			validFields = false;
		}
	}
	
	return validFields;
	/*
	if(validFields) {
		//alert("true");
		SendDiscountSMS();
		reloadPage();
		reloadPage();
	} else {
		//alert("false");
		return false;
	}*/
}

function validateSMSFields() {
	var validFields = true;
	if( validatecellphonewitherror(document.getElementById("txtfriend1"), 'cellphone_label_1')) {
	} 
    else {
		//alert("false 1");
		//return false; 
		validFields = false;
		}
	if( validatecellphonewitherror(document.getElementById("txtfriend2"), 'cellphone_label_2')) {
	} 
    else {
		//alert("false 2");
		//return false; 
		validFields = false;
		}
	if( validatecellphonewitherror(document.getElementById("txtfriend3"), 'cellphone_label_3')) {
	} 
    else { 
		//alert("false 3");
		//return false; 
		validFields = false;
		}
	if( validatecellphonewitherror(document.getElementById("txtfriend4"), 'cellphone_label_4')) {
	} 
    else { 
		//alert("false 4");
		//return false; 
		validFields = false;
	}
	
	if(validFields) {
		//alert("true");
		SendDiscountSMS();
		reloadPage();
		reloadPage();
    } 
    else {
		//alert("false");
		return false;
	}
}

function SendDiscountSMSWithValidation() {
	if( validatecellphonewitherror(document.getElementById("txtfriend1"), 'cellphone_label_1')) {
		SendDiscountSMS2(document.getElementById("txtfriend1"));
		reloadPage();
	}
	if( validatecellphonewitherror(document.getElementById("txtfriend2"), 'cellphone_label_2')) {
		SendDiscountSMS2(document.getElementById("txtfriend2"));
		//reloadPage();
	}
	if( validatecellphonewitherror(document.getElementById("txtfriend3"), 'cellphone_label_3')) {
		SendDiscountSMS2(document.getElementById("txtfriend3"));
		//reloadPage();
	}
	if( validatecellphonewitherror(document.getElementById("txtfriend4"), 'cellphone_label_4')) {
		SendDiscountSMS2(document.getElementById("txtfriend4"));
		//reloadPage();
	}
	return false;
}

function SendDiscountSMS() {
	SendDiscountSMS2(document.getElementById("txtfriend1"));
	SendDiscountSMS2(document.getElementById("txtfriend2"));
	SendDiscountSMS2(document.getElementById("txtfriend3"));
	SendDiscountSMS2(document.getElementById("txtfriend4"));
	
	//clear fields!
	/*
	document.getElementById("txtfriend1").value = "";
	document.getElementById("txtfriend2").value = "";
	document.getElementById("txtfriend3").value = "";
	document.getElementById("txtfriend4").value = "";
	*/
	return true;
}

function reloadPage() {
	//alert("test send exceeded");
	window.location.reload(true);
}

function validatecellphone(o) {
	value = o.value;
	if( value != "" ) {
		$.get("/AJAX/phone_validation.php", {number: cellnumber},
			function(data) {
				if(data != "true") {
					//$("label[for='cellphonen']").html(data);
					return 0;
				}
				else {
					//$("label[for='cellphonen']").html("");
					alert("" + data);
					o.focus();
					o.select();
					return 1;
				}
			});
    } 
    else {
		// If object value is empty, no need to validate, no data to validate.
		return 1;
	}
}

function checkemail(o) {
	value = o.value;
	$.ajax({
		url: "/AJAX/email_validator.php?email=" + value,
 		success: function(html) {
			//alert(html == "false");
			//	alert(html);
			if(html == "false") {
				//doesn't exists"
				return 0;
            } 
            else {
				// does exists
				alert("Email already exists, please type another");
				o.focus();
				o.select();
				return 1;
			}
			//Boolean(html);
  		},
		error: function(html){
			//success = html;
			return 0;
		}
	});
}

function checkemailwitherror(objTextFieldEmail, objErrorLabel, objRequired) {
	if(!objRequired) {
		//objRequried not set => Require VALIDATE
		
		value = objTextFieldEmail.value;
		$.ajax({
			url: "/AJAX/email_validator.php?email=" + value,
			success: function(html) {
				//alert(html == "false");
				//	alert(html);
				if(html == "false") {
					//doesn't exists"
					document.getElementById(objErrorLabel).innerHTML = "";
					return true;
	            } 
                else {
					// does exists
					//alert("Email already exists, please type another");
					document.getElementById(objErrorLabel).innerHTML = "Email aldreay exists, please type another";
					
					objTextFieldEmail.focus();
					objTextFieldEmail.select();
					return false;
				}
				//Boolean(html);
			},
			error: function(html){
				//success = html;
				return false;
			}
		});
		if(document.getElementById(objErrorLabel).innerHTML == "") {
            return true;
        } 
        else {
            return false;	
        }
    } 
    else if(objRequired == "false" ) {
		return true;
	}
}

function validatecountrywitherror(obj, objErrorLabel, objRequired) {
	value = $('#' + obj.id).val();
	
	if (value =="choose") {
		document.getElementById(objErrorLabel).innerHTML = "Please select a country!";
		obj.focus();
		
		return false;
    }
    else {
		document.getElementById(objErrorLabel).innerHTML = "";
		return true;
	}
}

// Name: createNewCustomerFromEmailOrCellphone
//
// Author: Christian
//
// Purpose: This functions check whatever a new customer should be created
//			using either email or cell phone. This selection is done by a 
//			radio button control. The user will be informed if the selected
//			options was not filled in correctly
//
// Arguments: objTextFieldCellphone - The ID of the cell phone text field
//			  objErrorLabel - The ID of the cell phone label field
//            objTextFieldEmail - The ID of the email text field
//			  objErrorLabel - The ID of the email text field
//			  objRadioButton - The ID of the radio button that controls the check
//
// Return: On Success - The customer is created
//		   On Failure - The user is informed about which information is missing.
function createNewCustomerFromEmailOrCellphone(objTextFieldCellphone,objErrorLabel,objTextFieldEmail,objErrorLabel,objRadioButton) {
	var radioButtonControl = document.getElementsByName(objRadioButton);
	var radioButtonSelected = radioButtonControl.value;
}

function validatecellphonewitherror(objTextFieldPhone, objErrorLabel ) {
	value = objTextFieldPhone.value;
	
	if( value != "" ) {
		var tsTimeStamp= new Date().getTime();
		
		$.get("/AJAX/phone_validation.php", {number: value,  time: tsTimeStamp},
			function(data) {
				if(data == "true") {
					//$("label[for='cellphonen']").html(data);
					document.getElementById(objErrorLabel).innerHTML = "";
					return false;
				}
				else {
					//$("label[for='cellphonen']").html("");
					document.getElementById(objErrorLabel).innerHTML = "" + data;
					objTextFieldPhone.focus();
					objTextFieldPhone.select();
					return false;
				}
			});
		if(document.getElementById(objErrorLabel).innerHTML == "") {
			return true;
        } 
        else {
			return false;	
		}
    } 
    else {
		// If object value is empty, no need to validate, no data to validate.
		document.getElementById(objErrorLabel).innerHTML = "";
		return true;
	}
}

function validatecellphoneonsubmit(objPhoneId, objErrorLabel, objRequired ) {
	var elm = document.getElementById(objPhoneId);
	value = elm.value; 
	
	if( value != "" || objRequired == "true" ) {
		$.get("/AJAX/phone_validation.php", {number: value},
			function(data) {
				if(data == "true") {
					//$("label[for='cellphonen']").html(data);
					document.getElementById(objErrorLabel).innerHTML = "";
					return true;
				}
				else {
					//$("label[for='cellphonen']").html("");
					document.getElementById(objErrorLabel).innerHTML = "" + data;
					elm.focus();
					elm.select();
					return false;
				}
			});
		if(document.getElementById(objErrorLabel).innerHTML == "") {
			//alert("succeded");
			return true;
        } 
        else {
			//alert("failed");
			return false;
        }
    }
    else {
		return true;	
	} 
}

function changeCurrency(currency) {
	//alert(currency);
	//location.href = location.href + "&currency=" + currency;
	
	$.ajax({
  		url: "/AJAX/changecurrency.php?cur=" + currency,
  		cache: false,
  		success: function(html){
    		//$("#dealerCountrySelect").html(html);
			//displaySMSStatus(html,left,top);
			//elm.value = "";
			//alert(html);
			//location.href = location.href;

			location.reload(true);
  		}
	});
}

function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber=true;
    var Char;
 
    for (i = 0; i < sText.length && IsNumber == true; i++) { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

function validatePhoneNumber(to) {
	//no code yet!
}

function SendDiscountSMS2(elm) {
	if(!elm) {
		return false;
	}
	send_to = elm.value;
	
	if (send_to == ""){
		return false;
	}
	
	var pos = $(elm).position();
	var left = pos.left + $(elm).width() + 10;
	var top = pos.top;
	
	if (send_to.substring(0,1) != "+") {
		displaySMSStatus("Numbers should start with countrycode. E.g. +45",left,top);
		return false;
	}
	
	if (!IsNumeric(send_to.substring(1))) {
		displaySMSStatus("Not a vaild number!",left,top);
		return false;
	}
	
	send_to = send_to.replace('+', 'X');
	//alert("sender til: " + send_to);
	//alert("VIRK NU!!!" + send_to);	
	var currentTime = new Date();
	
	$.ajax({
  		url: "/AJAX/send_discount_sms.php?send_to=" + send_to + "&nocache=" + currentTime,
  		cache: false,
  		success: function(html) {
    		//$("#dealerCountrySelect").html(html);
			displaySMSStatus(html,left,top);
			elm.value = "";
  		}
	});
}
		
function displaySMSStatus(msg,x,y) {
	var theBody = document.getElementsByTagName('body')[0];
	var _div = document.createElement('div');
	_div.innerHTML = "" + msg + "";
	_div.style.position = 'absolute';
	_div.style.textAlign = 'left';
	_div.style.border = 'solid 1px #B3B3AF';
	_div.style.color = '#FA8000';
	_div.style.padding = '2px';
	_div.style.background = '#F0F0EF';
	_div.style.fontSize = '10px';
	_div.style.width = "300px";
	_div.style.top = y;
	_div.style.left = x;
	theBody.appendChild(_div);
	
	$(_div).fadeOut(10000);
}

function getWindowHeight() {
    var windowHeight = 0;
    if (typeof(window.innerHeight) == 'number') {
        windowHeight = window.innerHeight;
    }
    else {
        if (document.documentElement && document.documentElement.clientHeight) {
            windowHeight = document.documentElement.clientHeight;
        }
        else {
            if (document.body && document.body.clientHeight) {
                windowHeight = document.body.clientHeight;
            }
        }
    }
    return windowHeight;
}

function displayError(msg) {
    /*
    if(document.getElementById("error_status_label")) {
        alert("Finn Tester!: err sta lbl set");	
    } 
    else {
        alert("Finn Tester!: err sta lbl not set");	
    }
    if(document.getElementById("current_login_status")){
        alert("Finn Tester!: login stat set");	
    } 
    else { 
        alert("Finn Tester!: login stat not set");	
    }
    if(document.getElementById("current_login_status").value != "failed"){
        alert("Finn Tester: current log stat not failed");
    } 
    else {
        alert("Finn Tester: current log stat failed");	
    }
    */
    if (document.getElementById("error_status_label") && (document.getElementById("current_login_status") && document.getElementById("current_login_status").value != "failed")) {
        document.getElementById("error_status_label").style.color = '#FF8000';
        document.getElementById("error_status_label").innerHTML = '' + unescape(msg);
    }
    else if (document.getElementById("login_error_status_label")) {
        document.getElementById("login_error_status_label").style.color = '#FF8000';
        document.getElementById("login_error_status_label").innerHTML = '' + unescape(msg);
    }
    else {
        /*
        if(document.getElementById("login_error_status_label")) {
            if(document.getElementById("current_login_status")) {
                if(document.getElementById("current_login_status").value == "failed") {
                } 
                else { 
                    if(document.getElementById("error_status_label")){
                        document.getElementById("error_status_label").style.color = '#FF8000';
                        document.getElementById("error_status_label").innerHTML = '' + unescape(msg);
                    }
                }
            }
        } 
        else {
        }
        */

        /*
        if(document.getElementById("error_status_label")){
            document.getElementById("error_status_label").style.color = '#FF8000';
            document.getElementById("error_status_label").innerHTML = '' + unescape(msg);
        } 
        else {
        */
            var theBody = document.getElementsByTagName('body')[0];
            var _div = document.createElement('div');
            _div.innerHTML = "" + msg + "";
            _div.style.position = 'absolute';
            _div.style.border = 'solid 1px #B3B3AF';
            _div.style.color = '#FA8000';
            _div.style.padding = '20px';
            _div.style.background = '#F0F0EF';
            _div.style.width = "500px";
            _div.style.top = getWindowHeight() / 3 + "px";
            _div.style.left = (($(window).width() / 2) - 250) + "px";
            theBody.appendChild(_div);

            $(_div).fadeOut(5000); // up from 5000
        //}
    }
}

//function to get query
function getParameterByName( name )  {  
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
	var regexS = "[\\?&]"+name+"=([^&#]*)";  
	var regex = new RegExp( regexS );  
	var results = regex.exec( window.location.href );  
	if( results == null )    
		return "";  
	else    
		return results[1];
}

//URL DECODE
function decode(encoded) {
	return decodeURIComponent(encoded.replace(/\+/g,  " "));
}

// DEALERMAP START
// MAP CLICK
function dealer_list(id) {
	$.ajax({
  		url: "/AJAX/dealerlist_getcountrylist.php?id=" + id,
  		cache: false,
  		success: function(html){
    		$("#dealerCountrySelect").html(html);
  		}
	});
	dealer_clearcities();
	dealer_cleardealers();
}

// REMOVE CITY-DDL
function dealer_clearcities() {
	$.ajax({
  		success: function(html) {
    		$("#dealerCitySelect").html("");
  		}
	});
}

// REMOVE DEALERS
function dealer_cleardealers() {
	$.ajax({
  		success: function(html) {
    		$("#dealer_list").html("");
  		}
	});
}

// COUNTRY LIST
function dealer_getcities(countryid) {
	$.ajax({
  		url: "/AJAX/dealerlist_getcitylist.php?id=" + countryid,
  		cache: false,
  		success: function(html) {
    		$("#dealerCitySelect").html(html);
  		}
	});
	dealer_getdealersincountry(countryid);
}

// COUNTRY LIST
function dealer_getdealersincountry(countryid) {
	$.ajax({
  		url: "/AJAX/dealerlist_getdealersfromcountry.php?id=" + countryid,
  		cache: false,
  		success: function(html) {
    		$("#dealer_list").html(html);
  		}
	});
}

// COUNTRY LIST + MAP CLICK
function dealer_getdealersincity(cityid) {
	$.ajax({
  		url: "/AJAX/dealerlist_getdealersfromcity.php?id=" + cityid,
  		cache: false,
  		success: function(html) {
    		$("#dealer_list").html(html);
  		}
	});
}

// DEALERMAP END
// Wisedealer Create Form END

function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber=true;
    var Char;
 
    for (i = 0; i < sText.length && IsNumber == true; i++) { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

function add_product_to_cart2(id, qty, handle, goodman) {
    if (IsNumeric(qty)){
	}
    else {
		qty = 1;
	}
	
	$.ajax({
  		url: "/AJAX/shoppingcart_add2.php?id=" + id + "&qty=" + qty + "&handle=" + handle+ "&goodman=" + goodman,
  		cache: false,
  		success: function(html){
    		$("#haastrup_cart_mini").html(html);
  		}
	});
}

function add_product_to_cart(id, price) {
	//alert("viser produkt: " + id);
	qty = $("#prod_qty"+id).val();
	if (IsNumeric(qty)){
	}
    else {
		qty = 1;
	}
	
	$.ajax({
  		url: "/AJAX/shoppingcart_add2.php?id=" + id + "&qty=" + qty + "&price=" + price,
  		cache: false,
  		success: function(html){
    		$("#haastrup_cart_mini").html(html);
  		}
	});
}

function clearShoppingCart() {
    $.ajax({
        url: "/AJAX/shoppingcart_update.php?change=empty&size=mini",
        cache: false,
        success: function (html) {
            $("#haastrup_cart_mini").html(html);
            $.ajax({
                url: "/AJAX/shoppingcart_update.php?change=empty&size=large",
                cache: false,
                success: function (html) {
                    $("#haastrup_cart_large").html(html);
                }
            });
        }
    });
}

function clearShoppingCart_old() {
    $.get("/AJAX/clear_cart.php", { cart: '' },
	function (data) {
	    parent.location.reload(true);
	});
}

function update_product_in_cart(key, change) {
    $.ajax({
        url: "/AJAX/shoppingcart_update.php?key=" + key + "&change=" + change + "&size=large",
  		cache: false,
  		success: function(html){
  		    $("#haastrup_cart_large").html(html);
  		    $.ajax({
  		        url: "/AJAX/shoppingcart_update.php?key=" + key + "&change=nothing&size=mini",
  		        cache: false,
  		        success: function (html) {
  		            $("#haastrup_cart_mini").html(html);
  		        }
  		    });
  		}
	});
}

function add_product_to_cart_large(id) {
	//alert("viser produkt: " + id);
	
	$.ajax({
  		url: "/AJAX/shoppingcart_add.php?id=" + id + "&basket=large",
  		cache: false,
  		success: function(html){
    		$("#haastrup_cart_large").html(html);
  		}
	});

}

function delete_product_from_cart(id) {
	//alert("viser produkt: " + id);
	$.ajax({
  		url: "/AJAX/shoppingcart_delete.php?id=" + id,
  		cache: false,
  		success: function(html) {
    		$("#haastrup_cart_large").html(html);
  		}
	});
}

function remove_one_product_from_cart(id,qty) {
	//alert("viser produkt: " + id);
	$.ajax({
  		url: "/AJAX/shoppingcart_remove_one.php?id=" + id + "&qty=" +qty,
  		cache: false,
  		success: function(html){
    		$("#haastrup_cart_large").html(html);
  		}
	});
}


// REGISTER SELLER START
function add_product_to_register_seller(id) {
	//alert("viser produkt: " + id);
	$.ajax({
  		url: "/AJAX/registerseller_addproduct.php?id=" + id,
  		cache: false,
  		success: function(html){
    		$("#haastrup_cart_large").html(html);
  		}
	});
}

function remove_product_from_register_seller(id) {
	//alert("viser produkt: " + id);
	$.ajax({
  		url: "/AJAX/registerseller_removeproduct.php?id=" + id,
  		cache: false,
  		success: function(html){
    		$("#haastrup_cart_large").html(html);
  		}
	});
}

// REGISTERSELLER END
// CUSTOMER-STATE-PROVINCE START
function toggle_state_province() {
	var country = $("#select2").val();
	if(country != "US" && country != "CA") {
		$(".stateprovinceRow").hide();
	}
	else {
		$(".stateprovinceRow").show();
	}
}
// CUSTOMER-STATE-PROVINCE END

function change_shipping_method() {
	// shipping type e.g. standard or express
	
	var type_elem = $("input[name=shipment_type]:checked").val();
	var shipment_cost_elem = $(".shipment_"+type_elem);
	// getting new value
	var shipment_cost = shipment_cost_elem.html();
	// eliminate thousand sep.
	var shipment_cost_last = shipment_cost.split(",").join("");
	
	//alert(shipment_cost_last);
	
	$.post("/AJAX/shoppingcart_change_shipping_type_and_price.php", { cost: shipment_cost_last, ship_method: type_elem });
	
	return true;
}

// SHIPPING START
// number formatting function
// copyright Stephen Chapman 24th March 2006, 22nd August 2008
// permission to use this function is granted provided
// that this copyright notice is retained intact

function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) {var x = Math.round(num * Math.pow(10,dec));if (x >= 0) n1=n2='';var y = (''+Math.abs(x)).split('');var z = y.length - dec; if (z<0) z--; for(var i = z; i < 0; i++) y.unshift('0'); if (z<0) z = 1; y.splice(z, 0, pnt); if(y[0] == pnt) y.unshift('0'); while (z > 3) {z-=3; y.splice(z,0,thou);}var r = curr1+n1+y.join('')+n2+curr2;return r;}

function toggle_shipment() {
	// shipping type e.g. standard or express
	var type_elem = $("input[name=shipment_type]:checked").val();
	// getting element from type-field class="shipment_{type_elem}" ## e.g. class="shipment_standard" class="shipment_express"
	var shipment_cost_elem = $(".shipment_"+type_elem);
	// getting new value
	var shipment_cost = shipment_cost_elem.html();
	// eliminate thousand sep.
	var shipment_cost_last = shipment_cost.split(",").join("");
	
	// shipping row in table ## getting element
	var old_cost_elem = $(".shipment_amount");
	// getting old value;
	var old_cost = old_cost_elem.html();
	// eliminate thousand sep.
	var old_cost_last = old_cost.split(",").join("");

	// total row in table ## getting element
	var total_elem = $(".shipment_totalincvatship_amount");
	// getting old total value
	var total = total_elem.html();
	// eleminate thousand sep.
	var total_last = total.split(",").join("");

	// setting new shipping price in shipping row ## and getting correct number format
	old_cost_elem.html(formatNumber(Number(shipment_cost_last),2,',','.','','','',''));
	
	// getting form elements
	var dibs = $("input[name='amount']");
	var cb = $("input[name='price']");
	
	// setting form values for dibs and c&b
	cb.val(total_last);
	dibs.val(total_last.split(".").join(""));
	
	// setting new_total with correct numberformat
	var new_total = Number(total_last)-Number(old_cost_last)+Number(shipment_cost_last);

	// changing in shipping in db
	$.post("AJAX/shoppingcart_shipping.php", { cost: shipment_cost_last, ship_method: type_elem });
	
	// changing total row with nu calculated value
	total_elem.html(formatNumber(new_total,2,',','.','','','',''));
	return true;
}
// SHIPPING END

// POPUP TO USE FOR SELECTING PRODUCTS TO DEALER
/***************************/

				
/***************************/

//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;

//loading popup with jQuery magic!
function loadPopup() {
    //loads popup only if it is disabled
    if (popupStatus == 0) {
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
	
        $("#backgroundPopup").fadeIn("slow");
        $("#popupContact").fadeIn("slow");
        popupStatus = 1;
    }
}

//disabling popup with jQuery magic!
function disablePopup() {
    //disables popup only if it is enabled
    if (popupStatus == 1) {
        $("#backgroundPopup").fadeOut("slow");
        $("#popupContact").fadeOut("slow");
        popupStatus = 0;
    }
}

//centering popup
function centerPopup() {
    //request data for centering
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#popupContact").height();
    var popupWidth = $("#popupContact").width();
    //centering
    $("#popupContact").css({
        "position": "absolute",
        //"top": windowHeight / 2 - popupHeight / 2,
        "top": "50px",
        //"left": windowWidth / 2 - popupWidth / 2
        "left": "350px"
    });
    //only need force for IE6

    $("#backgroundPopup").css({
        "height": windowHeight
    });

}



//function to test script
function testPopup() {
    var ofla = $('input:checked[name=products]').map(function () { return $(this).val(); }).get().join(",");
    alert(ofla + " ID: " + $('input:hidden[name=dealerID]').val());
}



//CONTROLLING EVENTS IN jQuery
$(document).ready(function () {
    //LOADING POPUP
    //Click the button event!	

    $("#addProductButton").click(function () {
        //centering with css
		
        centerPopup();
        //load popup
        loadPopup();
    });

    //CLOSING POPUP
    //Click the x event!
    $("#popupContactClose").click(function () {
        disablePopup();
        //testPopup();
        aRegisterSeller_add_products(0, $('input:hidden[name=dealerID]').val());
    });
    //Click out event!
    $("#backgroundPopup").click(function () {
        disablePopup();
        //testPopup();
        //aRegisterSeller_add_products(0, $('input:hidden[name=dealerID]').val());
        $("#frm_a_register_seller").submit();
    });
    //Press Escape event!
    $(document).keypress(function (e) {
        if (e.keyCode == 27 && popupStatus == 1) {
            disablePopup();
            //testPopup();
            aRegisterSeller_add_products(0, $('input:hidden[name=dealerID]').val());
        }
    });
}); 

// END PRODUCT POPUP
