var ajax_url = "ajax.php";

jQuery(document).ready(function() {

	// SLIDESHOW
    jQuery('div#slides').cycle({
		fx: 'fade',
		speed: 2500,
		timeout: 5000,
		delay: -2500,
		random: true
	});

	//INPUT VALUE SWAP
	jQuery(function() {
	    swapValues = [];
	    jQuery(".sv").each(function(i){
	        swapValues[i] = jQuery(this).val();
	        jQuery(this).focus(function(){
	            if (jQuery(this).val() == swapValues[i]) {
	                jQuery(this).val("");
	            }
	        }).blur(function(){
	            if (jQuery.trim(jQuery(this).val()) == "") {
	                jQuery(this).val(swapValues[i]);
	            }
	        });
	    });
	});

	//PRODMENU ACTIVE
	jQuery("ul#produktMeny li.active").parents("li").addClass("active");

	// PRODADD
	jQuery('.pdSubmit').bind('mousedown', function() {
		jQuery('.pdSubmit').addClass('clicked');
		jQuery('.prodAdd').addClass('loading');
		jQuery('.addCart').addClass('show');
	});

});

// DOM ready function because we should probably
// be doing this in the <head>
$(function() {
	$("input[type='date']").datepicker({ 
		dateFormat: 'yy-mm-dd',
		firstDay: '1',
		dayNamesMin: ['Søn', 'Man', 'Tir', 'Ons', 'Tor', 'Fre', 'Lør'],
		monthNames: ['Januar','Februar','Mars','April','Mai','Juni','Juli','August','September','Oktober','November','Desember'],
		nextText: '»',
		prevText: '«'
	});
});

// FORM DELAY
function delaySubmit(e, sec) {
   var elem = jQuery(e);
 if (elem.find('input[name=submitted]').length) {
   return true;
 }
 elem.append('<input type="hidden" name="submitted" value="yes" />');
 var id = "" + elem.attr('id');
 setTimeout("submitForm('"+id+"');", sec * 1000);
 return false;
}
function submitForm(id) {
   jQuery('#' + id).submit();
   return true;
}

// SJEKK REQ FIELDS
var requiredFields = {
	"byttpassord":["pass","pass2"],
	"glemtpassord":["AWA_login_bruker"],
	"blikunde":["firmanavn","kontaktperson_fornavn","kontaktperson_etternavn","besoks_adresse","postnr","poststed","epost","passord"],
	"kundeinfooppdater":["firmanavn","kontaktperson_fornavn","kontaktperson_etternavn","besoks_adresse","postnr","poststed","epost"],
	"kontaktoss":["navn","telefon","epost","melding"]
};
//onsubmit="return sjekkFelt(this, 'kontaktoss');"

function sjekkFelt(e, feltListe)
{
	var form = jQuery(e);
	var element;
	var success = true;
	if (requiredFields[feltListe] == undefined) {
		return true;
	}
	var feltName;
	var feltLowerCase;
	for (var felt in requiredFields[feltListe]) {
		feltName = requiredFields[feltListe][felt];
		element = form.find('[name="' + feltName + '"]');
		feltLowerCase = feltName.toLowerCase();
		if (
			( isEmail = 
				(element.is('input:text') || element.is('input:password') || element.is('input:file'))
			  && (((feltLowerCase != 'epost') && !element.val()) 
			   || ((feltLowerCase == 'epost') && (false == validateEmail(element.val()))))
			) 
		 || (element.is('input:checkbox') && !element.is(':checked'))
		 || (element.is('textarea') && !element.val())
		  )
		{
			//console.log("tomt felt " + element.attr('name'));
			element.addClass('error');
			success = false;
			element.one('focus', function() { jQuery(this).removeClass('error'); });
		}
	}
	return success;
}

function digitValueOnly(field)
{
	var element = jQuery(field);
	element.val(element.val().replace(/[^0-9+]/g, ''));
}

function validateEmail(email)
{
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return reg.test(email);
}

// Passordsjekk
function strength(password)
{
        var desc = new Array();
        desc[0] = "<font color=red>*</font>";
        desc[1] = "**";
        desc[2] = "***";
        desc[3] = "<font color=darkgreen>****</font>";
        desc[4] = "<font color=darkgreen>*****</font>";
        desc[5] = "<font color=darkgreen>******</font>";
var strength   = 0;
if (password.length > 6) strength++;
if ( ( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) ) ) strength++;
if (password.match(/\d+/)) strength++;
if ( password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) ) strength++;
if (password.length > 10) strength++;
document.getElementById("pwdesc").innerHTML = desc[strength];
document.getElementById("pwstrength").className = "strength" + strength;
}

function match(password,otherpassword)
{
if (password == otherpassword) {

	document.getElementById("match").innerHTML = "<img src=\"bilder/bilder/struktur_element/check.jpg\">";
}
else{
	document.getElementById("match").innerHTML = "<img src=\"bilder/bilder/struktur_element/cross.jpg\">";
}
}

// PRICECALC
var pricecalcIds = 0;

function pricecalcGetPrice(element) {
	return jQuery(element).parents(".product").find(".pricebuy strong span").text();
}

function pricecalcGetTitle(element) {
	return jQuery(element).parents(".product").find("h2 a").text();
}

function pricecalcGetMva(element) {
	return '25';
}

function stringToNum(num) {
	return num.replace(/,/, '.');
}

function numToString(num) {
	num = '' + num;
	return num.replace(/\./, ',');
}

function custRound(x,places) {
	// Created 1997 by Brian Risk.  http://brianrisk.com
	return (Math.round(x*Math.pow(10,places)))/Math.pow(10,places)
}

jQuery(function() {
	jQuery('.pricecalcOpen').bind("click", function(e) {
		title	= pricecalcGetTitle(this);
		price	= pricecalcGetPrice(this);
		//mva 	= pricecalcGetMva(this);

		/*
		position = new Array();
		position.push(e.pageX);
		position.push(e.pageY);
		*/
		
		pricecalcIds = jQuery('#pricecalcId').val();
		pricecalcIds = parseInt(pricecalcIds) + 1;
		jQuery('#pricecalcId').val(pricecalcIds);
		id = 'pricecalc' + pricecalcIds;
		
		priceCalcDialog = jQuery('pricecalcBlock').html();
		if ((priceCalcDialog == undefined) || 
			(priceCalcDialog.length < 1)) {
			priceCalcDialog = '<form onsubmit="return false;">'
							+ '	<div class="formContainer"><div class="formTittel">Innkjøpspris</div><div class="formVerdi"><input type="text" name="inPrice" disabled="disabled"/></div></div>'
							+ '	<div class="formContainer"><div class="formTittel">Faktor innkjøpspris</div><div class="formVerdi"><input type="text" name="factor"/></div></div>'
							+ '	<div class="formContainer"><div class="formTittel">Prosent til innkjøpspris</div><div class="formVerdi"><input type="text" name="percent"/></div></div>'
							+ '	<div class="formContainer"><div class="formTittel">Fortjeneste</div><div class="formVerdi"><input type="text" name="profit"/></div></div>'
							+ '	<div class="formContainer"><div class="formTittel">Utsalgspris</div><div class="formVerdi"><input type="text" name="outPrice"/></div></div>'
							+ '</form>';
		}

		jPriceCalcDialog = jQuery('<div title="Priskalkulator" />').attr("id", "pricecalcBlock");
		jPriceCalcDialog.append(priceCalcDialog);

		jPriceCalcDialog.find('.pricecalcTitle').text(title);

		jPriceCalcDialog.find('input[name=inPrice]').val(numToString(price));
		jPriceCalcDialog.find('input[name=factor]').val(numToString(1.3));

		jPriceCalcDialog.find('input[type=text]').bind('keypress', function(e) {
			if (e.which == 13) {
				pricecalcProcess(this);
			} else {
				//console.log('press ' + e.which);
			}
		});
		
		pricecalcProcess(jPriceCalcDialog.find('input[name=factor]'));
		
		//{ 'position': position, 'title': title, 'dialogClass': 'pricecalc'});
		options = { 'title': title, 'dialogClass': 'pricecalc'};
		jPriceCalcDialog.dialog(options);
	});
});

function pricecalcProcess(element) {
	form = new PriceCalcElement(element);
	priceCalc = new PriceCalc(form.getInPrice(), form.getPercentage(), form.getFactor(), form.getMva(), form.getProfit(), form.getOutPrice());
	priceCalc.calculateByName(form.name);
	form.setPercentage(priceCalc.percent);
	form.setFactor(priceCalc.factor);
	form.setOutPrice(priceCalc.outPrice);
	form.setProfit(priceCalc.profit);
}

function PriceCalcElement(element)
{
	this.form;
	this.name;
	
	this.setFormElement = function(element)
	{
		element = jQuery(element);
		this.form = element.parents('form');
		this.name = element.attr('name');
		//return this;
	};
	
	this.setFormElement(element);
	
	this.setInPrice = function(value)
	{
		this.form.find('input[name=inPrice]').val(numToString(value));
		return this;
	};
	
	this.getInPrice = function()
	{
		value = this.form.find('input[name=inPrice]').val();
		value = value.replace(/\s+/g, '');
		//console.log ('getInPrice' + value);
		//console.log('getPercentage ' + value + ' stringToNum ' + stringToNum(value));
		return stringToNum(value);
	};
	
	this.setPercentage = function(value)
	{
		//console.log('setPercentage ' + value + ' numToString ' + numToString(value));
		value = custRound(value, 2);
		this.form.find('input[name=percent]').val(numToString(value));
		return this;
	};
	
	this.getPercentage = function()
	{
		value = this.form.find('input[name=percent]').val();
		if (value == undefined) {
			value = '';
		}
		//console.log('getPercentage ' + value + ' stringToNum ' + stringToNum(value));
		return stringToNum(value);
	};
	
	this.setFactor = function(value)
	{
		//console.log('setFactor ' + value + ' numToString ' + numToString(value));
		value = custRound(value, 3);
		this.form.find('input[name=factor]').val(numToString(value));
		return this;
	};
	
	this.getFactor = function()
	{
		value = this.form.find('input[name=factor]').val();
		if (value == undefined) {
			value = '';
		}
		//console.log('getPercentage ' + value + ' stringToNum ' + stringToNum(value));
		return stringToNum(value);
	};
	
	this.setProfit = function(value)
	{
		//console.log('setProfit ' + value + ' numToString ' + numToString(value));
		value = custRound(value, 2);
		this.form.find('input[name=profit]').val(numToString(value));
		return this;
	};
	
	this.getProfit = function()
	{
		value = this.form.find('input[name=profit]').val();
		if (value == undefined) {
			value = '';
		}
		//console.log('getProfit ' + value + ' stringToNum ' + stringToNum(value));
		return stringToNum(value);
	};
	
	this.setOutPrice = function(value)
	{
		//console.log('setOutPrice ' + value + ' numToString ' + numToString(value));
		value = custRound(value, 2);
		this.form.find('input[name=outPrice]').val(numToString(value));
		return this;
	};
	
	this.getOutPrice = function()
	{
		value = this.form.find('input[name=outPrice]').val();
		if (value == undefined) {
			value = '';
		}
		//console.log('getOutPrice ' + value + ' stringToNum ' + stringToNum(value));
		return stringToNum(value);
	};
	
	this.setMva = function(value)
	{
		//this.form.find('input[name=outPrice]').val(numToString(value));
		return this;
	};
	
	this.getMva = function()
	{
		value = '25';
		/*
		mva = this.form.find('input[name=mva]');
		if ((mva.length > 0) && (mva.val() != '')) {
			value = mva.val();
		}
		*/
		//console.log('getMva ' + value + ' stringToNum ' + stringToNum(value));
		return stringToNum(value);
		//return this.form.find('input[name=outPrice]').val();
	};
}

function PriceCalc(pInPrice, pPercent, pFactor, pMva, pProfit, pOutPrice)
{
	this.inPrice;
	this.percent;
	this.factor;
	this.mva;
	this.profit;
	this.outPrice;
	
	this.setValues = function(pInPrice, pPercent, pFactor, pMva, pProfit, pOutPrice)
	{
		this.inPrice = parseFloat(pInPrice);
		this.percent = parseFloat(pPercent);
		this.factor = parseFloat(pFactor);
		this.mva = parseFloat(pMva);
		this.profit = parseFloat(pProfit);
		this.outPrice = parseFloat(pOutPrice);
	};
	
	this.setValues(pInPrice, pPercent, pFactor, pMva, pProfit, pOutPrice);
	
	this.calculateByName = function(name)
	{
		switch(name) {
			case 'factor':
				return this.calculateFromFactor();
			case 'percent':
				return this.calculateFromPercentage();
			case 'outPrice':
				return this.calculateFromOutPrice();
			case 'profit':
				return this.calculateFromProfit();
			default:
				return false;
		}
	};
	
	this.calculateFromFactor = function()
	{
		this.profit = (this.inPrice * this.factor) - this.inPrice;
		this.percent = (this.factor - 1) * 100;
		this.outPrice = (this.inPrice + this.profit) * percentToFactorPositive(this.mva);
		return this;
	};
	
	this.calculateFromPercentage = function()
	{
		this.factor = percentToFactorPositive(this.percent);
		this.profit = (this.inPrice * this.factor) - this.inPrice;
		this.outPrice = (this.inPrice + this.profit) * percentToFactorPositive(this.mva);
		
		return this;
	};
	
	this.calculateFromOutPrice = function()
	{
		this.profit = this.outPrice * percentToFactorNegative(this.mva) - this.inPrice;
		this.factor = (this.profit + this.inPrice) / this.inPrice;
		this.percent = positiveFactorToPercent(this.factor);
		return this;
	};
	
	this.calculateFromProfit = function()
	{
		this.factor = (this.profit + this.inPrice) / this.inPrice;
		this.percent = positiveFactorToPercent(this.factor);
		this.outPrice = (this.inPrice + this.profit) * percentToFactorPositive(this.mva);
		return this;
	};
}

function percentToFactorNegative(percent)
{
	return (100 / (1 + (percent / 100))) / 100;
}

function positiveFactorToPercent(factor)
{
	return (factor - 1) * 100;
}

function percentToFactorPositive(percent)
{
	return 1 + (percent / 100);
}


/**
 * Uhu
 */

function nrFormat(n,sep) {
	var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
	sValue=n+'';

	if (sep === undefined) {sep=' ';}
	while(sRegExp.test(sValue)) {
	sValue = sValue.replace(sRegExp, 'jQuery1'+sep+'jQuery2');
	}
	sValue=sValue.replace(".", ",");
	return sValue;
};

