function checkHugeSearchFieldBlur(value)
{
	if(trim(value) == "")
	{
		document.getElementById("hugeSearchBox").value = "Chassinummer, modell, fabrikat...";
	}
}

function checkHugeSearchFieldClick(value)
{
	if(value == "Chassinummer, modell, fabrikat...")
	{
		document.getElementById("hugeSearchBox").value = "";
	}
}

function trim(val) 
{
   var ret = val.replace(/^\s+¦\s+$/g, "");
   ret = ret.replace(/\s+$/, '');

   return ret;
}

function submitEnter(buttonID, e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	
	if (keycode == 13)
  {
   document.getElementById(buttonID).click();
   return false;
  }
	else
	   return true;
}


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

   if(reg.test(emailValue) == false) 
   {
      return false;
   }
   else
   {
   	return true;
   }
}

function jumpToAnchor(anchor) 
{
  window.location = window.location = String(window.location).replace(/\#.*$/, "") + anchor;
}

function getRandomBroadcastMessage(messageString)
{
	var messages = messageString.split("|");
	var messageLength = messages.length - 1;
	
	var randomMessage = Math.floor(Math.random()*messageLength);
	
	var randomMessageArray = messages[randomMessage].split(";");
	return randomMessageArray;
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function showHideCreateAccountDiv()
{
	if(document.getElementById("createAccountDiv").style.display == "none")
	{
		document.getElementById("createAccountDiv").style.display = "";
		document.getElementById("loginDiv").style.display = "none";
	}
	else
	{
		document.getElementById("createAccountDiv").style.display = "none";
	}
}

function showHideLoginDiv()
{
	if(document.getElementById("loginDiv").style.display == "none")
	{
		document.getElementById("loginDiv").style.display = "";
		document.getElementById("createAccountDiv").style.display = "none";
	}
	else
	{
		document.getElementById("loginDiv").style.display = "none";
	}
}

// Selectedvalue = if you want a value to be selected from start. May be empty
function updateKommuner(dropDown, curSelectedValue)
{
	
	var selectedIndex = dropDown.selectedIndex;
	var selectedValue = dropDown.options[selectedIndex].value;
	
	// HTML-objects
	var kommunDropDown = document.getElementById("kommun");
	var areaDropDown = document.getElementById("area");
	
	// Empty kommunDropDown
	removeOptions(kommunDropDown);
	
	// Empty areaDropDown
	if(areaDropDown.style.visibility == "visible")
	{
		removeOptions(areaDropDown);
	}
	
	// Hide area dropdown
	areaDropDown.style.visibility = "hidden";
	
	// Get kommuner
	var kommuner = String("" + AJAXGetKommuner(selectedValue));
	kommunerArray = kommuner.split("*");
	
	// Add "standard" text to kommun dropdown
	addOption(kommunDropDown, "Välj kommun", "");
	
	// Loop through and add kommuner to kommunDropDown
	var curSelectedIndex;
	for(var i = 0; i < kommunerArray.length - 1; i++)
	{
		var values = kommunerArray[i].split(",");
		addOption(kommunDropDown, values[1], values[0]);

		if(values[0] == curSelectedValue)
		{
			curSelectedIndex = i + 1; // + 1 because a standardvalue is shown "välj kommun"
		}
	}
	
	// If curSelectedIndex is set
	if(curSelectedIndex)
	{
		kommunDropDown.selectedIndex = curSelectedIndex;
	}
}

function updateAreas(dropDown, curSelectedValue)
{
	var selectedIndex = dropDown.selectedIndex;
	var selectedValue = dropDown.options[selectedIndex].value;
	
	// HTML-objects
	var areaDropDown = document.getElementById("area");
	
	// Empty areaDropDown
	removeOptions(areaDropDown);

	// Get areas
	var areas = AJAXGetAreas(selectedValue);
	areasArray = areas.split("*");
	
	// Set "standard" text
	addOption(areaDropDown, "Välj område", "");
	
	// Check if kommun contains areas
	if(areasArray.length > 1)
	{
		areaDropDown.style.visibility = "visible";
		
		// Loop through and add kommuner to kommunDropDown
		var curSelectedIndex;
		for(var i = 0; i < areasArray.length - 1; i++)
		{
			var values = areasArray[i].split(",");
			addOption(areaDropDown, values[1], values[0]);
			
			if(values[0] == curSelectedValue)
			{
				curSelectedIndex = i + 1; // + 1 because a standardvalue is shown "välj kommun"
			}
		}
		
		// If curSelectedIndex is set
		if(curSelectedIndex)
		{
			areaDropDown.selectedIndex = curSelectedIndex;
		}
	}
	else
	{
		areaDropDown.style.visibility = "hidden";
	}
}

function redirect(location)
{
	window.location = location;
}

function validateLogin()
{
	// Set login to 1 and newUserAccount to 0
	document.getElementById("login").value = 1;
	if(document.getElementById("newUserAccount")) // Make sure that id exist
	{
		document.getElementById("newUserAccount").value = 0;
	}
	
	// Check if username is empty
	if(!checkFieldEmpty(document.getElementById("username").value, "username"))
	{
		Form.errors = 1;
		Form.emptyFields = 1;
	}
	
	// Check if password is empty
	if(!checkFieldEmpty(document.getElementById("password").value, "password"))
	{
		Form.errors = 1;
		Form.emptyFields = 1;
	}
}

function validateLoginPanel()
{
	// Set login to 1 and newUserAccount to 0
	document.getElementById("login").value = 1;
	if(document.getElementById("newUserAccount")) // Make sure that id exist
	{
		document.getElementById("newUserAccount").value = 0;
	}
	
	// Check if username is empty
	if(!checkFieldEmpty(document.getElementById("usernamePanel").value, "usernamePanel"))
	{
		Form.errors = 1;
	}
	
	// Check if password is empty
	if(!checkFieldEmpty(document.getElementById("passwordPanel").value, "passwordPanel"))
	{
		Form.errors = 1;
	}
}

function resetErrors()
{
	Form.errors = 0;
}

function validateCreateAccount(fields)
{
	// Set login to 0 and newUserAccount to 1
	if(document.getElementById("login")) // Make sure id exist
	{
		document.getElementById("login").value = 0;
	}
	document.getElementById("newUserAccount").value = 1;
	
	// Check that terms are accepted
	if(document.getElementById("userAgree").checked == true)
	{
		document.getElementById("validateuserAgree").setAttribute("src", "images/ok.png");
	}
	else
	{
		Form.errors = 1;
		document.getElementById("validateuserAgree").setAttribute("src", "images/no.png");
	}
	
	fieldsArray = fields.split(",");
	
	// Loop through and check for each
	for(var i = 0; i < fieldsArray.length; i++)
	{
		// Check if field is empty
		if(!checkFieldEmpty(document.getElementById(fieldsArray[i]).value, fieldsArray[i]))
		{
			Form.errors = 1;
			Form.emptyFields = 1;
		}
		
		// Check if newUsername should be checked, if it is, check username
		if(fieldsArray[i] == "newUsername")
		{
			// AJAX-check
			if(AJAXCheckUsername(document.getElementById(fieldsArray[i]).value) == 0)
			{
				Form.errors = 1;
				document.getElementById("validatenewUsername").setAttribute("src", "images/no.png");
				document.getElementById("liRegisterUsernameExistError").style.display = "";
			}
			else
			{
				document.getElementById("liRegisterUsernameExistError").style.display = "none";
			}
		}
		
		// Check if email should be checked, if it is, check email
		if(fieldsArray[i] == "email")
		{
			// AJAX-check
			if(AJAXCheckEmail(document.getElementById(fieldsArray[i]).value) == 0)
			{
				Form.errors = 1;
				document.getElementById("validateemail").setAttribute("src", "images/no.png");
				document.getElementById("liRegisterEmailExistError").style.display = "";
			}
			else
			{
				document.getElementById("liRegisterEmailExistError").style.display = "none";
			}
			
			
			// Expression check
			if(validateEmail(document.getElementById(fieldsArray[i]).value) == false)
			{
				Form.errors = 1;
				document.getElementById("validateemail").setAttribute("src", "images/no.png");
				document.getElementById("liRegisterWrongEmailError").style.display = "";
			}
			else
			{
				document.getElementById("liRegisterWrongEmailError").style.display = "none";
			}
		}
		
		// Check if newPassword should be checked, if it is, check passwords equal
		if(fieldsArray[i] == "newPassword")
		{
			if(checkFieldEmpty(document.getElementById("newPassword").value, "newPassword"))
			{
				if(!checkFieldsEqual(document.getElementById("newPassword").value, document.getElementById("repeatPassword").value, "repeatPassword"))
				{
					Form.errors = 1;
				}
			}
			
			// Check that password is between 8-20 characters and contains at least 1 digit.
			var passwordErrors = AJAXCheckPassword(document.getElementById("newPassword").value);
			if(passwordErrors != 1)
			{
				Form.errors = 1;
				document.getElementById("validatenewPassword").setAttribute("src", "images/no.png");
				document.getElementById("liRegisterPasswordError").style.display = "";
				
			}
			else
			{
				document.getElementById("liRegisterPasswordError").style.display = "none";
			}
		}
		
	}
}

function validateErrors(errors, emptyErrors, formID, emptyErrorsID)
{
	if(errors == 0)
	{
		document.getElementById(formID).submit();
	}
	
	if(emptyErrorsID != "null")
	{
		if(emptyErrors > 0)
		{
			document.getElementById(emptyErrorsID).style.display = "";
		}
		else
		{
			document.getElementById(emptyErrorsID).style.display = "none";
		}
	}
}

function newPage(url,width,height)
{
	var egenskaper;
	
	egenskaper="toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no";
	egenskaper+=",width="+width;
	egenskaper+=",height="+height;
	unik=new Date();
	unik=unik.getSeconds()+"_"+unik.getMinutes()+"_"+unik.getHours();
	window.open(url,unik,egenskaper);
}

function addOption(selectbox, text, value )
{
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	selectbox.options.add(optn);
}

function removeOptions(dropDown)
{
	var length = dropDown.length;

	for (i = 0; i < length; i++) 
	{
		 dropDown.remove(0);
		 
	}
}

function createCookie(name,value,hours) 
{
	if (hours) {
		var date = new Date();
		date.setTime(date.getTime()+(hours*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) 
{
	createCookie(name,"",-1);
}

function addShowCategoryCookie(categoryID)
{
	// Get cookie
	var currentCookie = readCookie("showCategoryArray");
	
	if(currentCookie)
	{
		// Set cookie to array
		var cookieArray = currentCookie.split(",");
	
		for(var i = 0, len = cookieArray.length - 1; i < len; i++)
		{
			if(cookieArray[i] == categoryID)
			{
				return true;
			}
		}
		
		currentCookie += categoryID + ",";
	}
	else
	{
		currentCookie = categoryID + ",";
	}
	
	
	
	createCookie("showCategoryArray", currentCookie, 12);
}

function removeShowCategoryCookie(categoryID)
{
	// Get cookie
	var currentCookie = readCookie("showCategoryArray");
	
	var newCookieValue = "";
	
	if(currentCookie)
	{
		// Set cookie to array
		var cookieArray = currentCookie.split(",");
	
		for(var i = 0, len = cookieArray.length - 1; i < len; i++)
		{
			if(cookieArray[i] != categoryID)
			{
				// set new value
				newCookieValue += cookieArray[i] + ",";
			}
		}
		
		createCookie("showCategoryArray", newCookieValue, 12);
	}
}

// Type 1 is headcategory, type 2 is other category
function changeViewCategory(ID, type)
{
	var image;
	var name = "categoryViewIMG" + ID;
	
	if(document.getElementById(ID).style.display == "none")
	{
		expandCategory(ID);
		addShowCategoryCookie(ID);

		if(type == 1)
		{
			image = "include/images/arrow2.jpg";
		}
		else
		{
			image = "include/images/minus.png";
		}
		
		changeViewCategoryImage(name, image);
	}
	else
	{
		minimizeCategory(ID);
		removeShowCategoryCookie(ID);
		
		if(type == 1)
		{
			image = "include/images/arrow.jpg";
		}
		else
		{
			image = "include/images/plus2.png";
		}
		
		changeViewCategoryImage(name, image);
	}
	
}

function changeViewCategoryImage(ID, image)
{
	document.getElementById(ID).setAttribute("src", image);
}

function minimizeCategory(ID)
{
	document.getElementById(ID).style.display = "none";
}

function expandCategory(ID)
{
	document.getElementById(ID).style.display = "";
	document.getElementById(ID).style.visibility = "visible";
	document.getElementById(ID).style.position = "relative";
	
	// document.getElementById(ID).style.position = "relative"; Denna borde vara med på något sätt, har man den med som den är här så visas ingenting i ie7 dock, har man inte med den så skrivs divar över varandra
}


function AJAXCheckUsername(username)
{

  var HTTPRequest = makeHTTPRequestWait('checkUsername=1' + '&action=AGeneral', 	'username=' + username);

	return HTTPRequest.responseText;
}

function AJAXGetBroadcastMessages()
{

  var HTTPRequest = makeHTTPRequestWait('getBroadCastMessages=1' + '&action=AGeneral');

	return HTTPRequest.responseText;
}

function AJAXCheckPassword(password)
{

  var HTTPRequest = makeHTTPRequestWait('checkPassword=1' + '&action=AGeneral', 	'password=' + password);

	return HTTPRequest.responseText;
}

function AJAXCheckEmail(email)
{
  var HTTPRequest = makeHTTPRequestWait('checkEmail=1' + '&action=AGeneral', 	'email=' + email);
	
	return HTTPRequest.responseText;
}

function AJAXCheckEmailEdit(email, currentEmail)
{
  var HTTPRequest = makeHTTPRequestWait('checkEmailEdit=1' + '&action=AGeneral', 	'email=' + email + '&currentEmail=' + currentEmail);

	
	return HTTPRequest.responseText;
}

function AJAXCheckUsernameEdit(username, userID)
{
  var HTTPRequest = makeHTTPRequestWait('checkUsernameEdit=1' + '&action=AGeneral', 	'username=' + username +
																																									'&userID=' + userID);
	return HTTPRequest.responseText;
}

function AJAXGetKommuner(lanID)
{
  var HTTPRequest = makeHTTPRequestWait('getKommuner=1' + '&action=AGeneral', 	'lanID=' + lanID);
	
	return HTTPRequest.responseText;
}

function AJAXCheckSaleCode(saleCode)
{
  var HTTPRequest = makeHTTPRequestWait('checkSaleCode=1' + '&action=AGeneral', 	'saleCode=' + saleCode);

	return HTTPRequest.responseText;
}

function AJAXCheckSaleCodeEdit(saleCode, curSaleCode)
{

  var HTTPRequest = makeHTTPRequestWait('checkSaleCodeEdit=1' + '&action=AGeneral', 	'saleCode=' + saleCode + 
  																																										'&curSaleCode=' + curSaleCode);
	return HTTPRequest.responseText;
}

function AJAXGetProductSubCategories(categoryID)
{
  var HTTPRequest = makeHTTPRequestWait('getCategorySubCategories=1' + '&action=AGeneral', 	'categoryID=' + categoryID);

	return HTTPRequest.responseText;
}

function AJAXGetProducts(subCategory, categoryID)
{
  var HTTPRequest = makeHTTPRequestWait('getProducts=1' + '&action=AGeneral', 	'subCategory=' + subCategory +
  																																							'&categoryID=' + categoryID);

	return HTTPRequest.responseText;
}

function AJAXGetAreas(kommunID)
{
  var HTTPRequest = makeHTTPRequestWait('getAreas=1' + '&action=AGeneral', 	'kommunID=' + kommunID);
	
	return HTTPRequest.responseText;
}

	
/*
		Functions (class in JS) for errorhandling
*/
function ErrorMessageHandler()
{
	this.errorMessages = new Array();
}

function changeErrorMessagesState(fieldNr, messageNr, value)
{
	// Check if this error message exists, else create it
	if(!this.errorMessages[fieldNr])
	{
		this.errorMessages[fieldNr] = new Array();;
		this.errorMessages[fieldNr][1] = messageNr;
		this.errorMessages[fieldNr][2] = 0;
	}
	
	// change state
	this.errorMessages[fieldNr][2] = value;
	
}

function printErrorMessages(errorBoxID)
{
	if(!errorBoxID)
	{
		errorBoxID = "error";
	}
	
	var showErrorBox = 0;
	
	// Array that contains each error messages and how many times it should be displayed (0 meands hidden and all values higher than 0 means visible
	showErrorMessages = new Array();
	
	for(curErrorMessage in this.errorMessages)
	{
		
		// Cur showErrorMessage is null, set to 0
		if(showErrorMessages[this.errorMessages[curErrorMessage][1]] == null)
		{
			showErrorMessages[this.errorMessages[curErrorMessage][1]] = 0;
		}
		
		if(this.errorMessages[curErrorMessage][2] != null)
		{
			
			if(this.errorMessages[curErrorMessage][2] > 0)
			{
				showErrorBox++;
				showErrorMessages[this.errorMessages[curErrorMessage][1]]++;
			}
			else
			{
				// showErrorMessages[this.errorMessages[curErrorMessage][1]]--;
			}
		}
	}
	
	// If showErrorBox is bigger than 0, show
	if(showErrorBox < 1)
	{
		// Hide errorbox
		document.getElementById(errorBoxID).style.visibility = "hidden";
	}
	else
	{
		// Show errorbox
		document.getElementById(errorBoxID).style.visibility = "visible";
	}
	
	// Show/hide errors
	// Loop through showErrorMessages
	for(curErrorMessage in showErrorMessages)
	{
		if(showErrorMessages[curErrorMessage] > 0)
		{
			// Show specific error
			document.getElementById(errorBoxID + "errorNr" + curErrorMessage).style.visibility = "visible";
			document.getElementById(errorBoxID + "errorNr" + curErrorMessage).style.position = "relative";
		}
		else
		{
			// Hide specific error
			document.getElementById(errorBoxID + "errorNr" + curErrorMessage).style.visibility = "hidden";
			document.getElementById(errorBoxID + "errorNr" + curErrorMessage).style.position = "absolute";
		}

	}
}

function checkFieldsEqual(field1, field2, picID)
{
	// Set picID
	var picID = picID + "Validate";
	
	if(field1 == field2)
	{
		document.getElementById(picID).setAttribute("src", "images/ok.png");
		
		return true;
	}
	else
	{
		document.getElementById(picID).setAttribute("src", "images/no.png");
		
		return false;
	}
}

function checkFieldEmpty(value, picID)
{
	// Set picID
	var picID = picID + "Validate";
	value = trim(value);
	
	if(value)
	{
		document.getElementById(picID).setAttribute("src", "images/ok.png");
		
		return true;
	}
	else
	{
		document.getElementById(picID).setAttribute("src", "images/no.png");
		
		return false;
	}
	
}

function showErrorMessage(message)
{
	// Show errorbox
	document.getElementById("error").style.visibility = "visible";
	document.getElementById("error").style.position = "relative";
	
	// Get innerhtml
	currentErrorMessage = document.getElementById("errormessage").innerHTML;
	
	// Set new message
	currentErrorMessage += "<p class='errortext'>" + message + "</p>";
	document.getElementById("errormessage").innerHTML = currentErrorMessage;
}

function hideErrorMessage()
{
	// Hide errorbox
	document.getElementById("error").style.visibility = "hidden";
	document.getElementById("error").style.position = "absolute";
	
	// Set empty innerhtml
	document.getElementById("errormessage").innerHTML = "";
}
/*
		END ERROR HANDLING
*/

function getYearsInSelect(name, startYear)
{
	if(!startYear)
	{
		var d = new Date();
		startYear = d.getFullYear(); 
	}
	
	html = "<select id='" + name + "' name='" + name + "'>";

	for(i = startYear; i <= (startYear + 1); i++)
	{
		html += "<option value='" + i + "'>" + i + "</option>";
	}
	
	html += "</select>";
	
	return html;
}

function imposeMaxLength(Object, MaxLen)
{

  if ( Object.value.length > MaxLen )
  {
    Object.value = Object.value.substring( 0, MaxLen );
    alert( "Maxl\344ngden f\366r detta f\344lt \344r " + MaxLen + " tecken." );
    return false;
  }
}
