// The next line enables jQuery IntelliSense in Visual Studio:
/// <reference path="/common/js/IntelliSense/jquery-1.3.1-vsdoc.js" />

$(document).ready(function() {
	
	$("a.fancybox-toggle").fancybox({
        'hideOnContentClick': false,
        'frameWidth': 700,
        'frameHeight': 450,
        'padding': 5
    });
	
	$("a#single_2").fancybox({
		'zoomOpacity'			: true,
		'overlayShow'			: false,
		'zoomSpeedIn'			: 500,
		'zoomSpeedOut'			: 500
	});
	
	$("a#pakbon-popup").fancybox({
		'zoomOpacity'			: true,
		'overlayShow'			: false,
		'zoomSpeedIn'			: 500,
		'zoomSpeedOut'			: 500,
		'frameWidth'			: 520,
        'frameHeight'			: 420
	});
	
	
	jQuery(function(){
        var SelfLocation = window.location.href.split('?');
        switch (SelfLocation[1]) {
          case "justify_right":
            jQuery(".megamenu").megamenu({ 'justify':'right' });
            break;
          case "justify_left":
          default:
            jQuery(".megamenu").megamenu();
    	}
	});
	  
	  
	$("select#kleur-select").change(function() {
	
		// show stock messages
		ShowStockMessages(this.options[this.selectedIndex].value);
		
		// disable input when out of stock
		DisableInputWhenOutOfStock(this.options[this.selectedIndex].value);
		
	});
	
	
	$("a.setcoloroption").click(function() {
		
		// get clicked color id
		clickedId = this.id
		
		// set option to selected
		objOptions = document.bestelformulier.kleur.options;
		for(i=0; i < objOptions.length; i++) {
			myOption = objOptions[i];
			myOption.selected = false;
			if (myOption.value == clickedId) {
				myOption.selected = true;
			}
		}
		
		// show stock messages
		ShowStockMessages(clickedId);
		
		// disable input when out of stock
		DisableInputWhenOutOfStock(clickedId);
			
	});
	
	
	
	$("div.tooltip").tooltip({ 
		track: true, 
		delay: 0, 
		opacity: 0,
		top: -200, 
   		left: 30,
		showURL: false, 
		bodyHandler: function() { 
     		var myRel =  $(this).attr("rel");
			if (this.id.indexOf("-and-") > -1) {
				var colorcombination = this.id
				var firstcolor = colorcombination.substring(0, colorcombination.indexOf("-and-"));
				var secondcolor = colorcombination.substring(colorcombination.indexOf("-and-")+5);
				return "<h3>"+ myRel +"</h3><img src='/images/kleuren/"+ firstcolor + "_150.jpg'/><img src='/images/kleuren/"+ secondcolor + "_150.jpg'/>"; 
			} else {
				return "<h3>"+ myRel +"</h3><img src='/images/kleuren/"+ this.id + "_150.jpg'/>"; 
			}
   		} 
	}); 


	$("button.removeall").click(function() {
		if (confirm('Weet u zeker dat uw winkelwagen helemaal wilt leegmaken?')) {
			$("input.quantity").attr("value", "0");
			// Remove all other buttons because IE6 passes ALL <button type="submit"> elements back to the server on submit instead of just the clicked one.
			$("button:not(.removeall)").remove();
			return true;
		} else {
			return false;
		}
	});

	$("button.herberekenen").click(function() {
		// Remove all other buttons because IE6 passes ALL <button type="submit"> elements back to the server on submit instead of just the clicked one.
		$("button:not(.herberekenen)").remove();
	});
	
	$("a#toon-uitleg-verzendkosten").click(function() {
		$("#uitleg-verzendkosten").slideToggle();
	});

	$("img.add_quantity").click(function() {
		AddQuantity(this.id.replace('add_', ''), this);
	});

	$("img.subtract_quantity").click(function() {
		SubtractQuantity(this.id.replace('subtract_', ''), this);
	});
	
	$("img.delete_quantity").click(function() {
		DeleteQuantity(this.id.replace('delete_', ''), this);
	});
		
});


function ShowStockMessages(myValue)
{
	// hide all stock messages
	$(".hidemessage").hide();
	// show stock message for color
	myValue = myValue.replace(".", "_");
	$(".message_"+ myValue).show();
}

function DisableInputWhenOutOfStock(selectedItemDimension)
{
	selectedItemDimensionEscaped = selectedItemDimension.replace(".", "_")

	for (i=0;i < objSizeColorArrays.length;i++)
	{
		myArray = objSizeColorArrays[i];
		size = myArray[0];
		itemDimensionSize = myArray[1];
		color = myArray[2];
		itemDimension = myArray[3];
		stock = myArray[4];
		
		// get the selected color input divs and hide when out of stock 
		if (itemDimension == selectedItemDimensionEscaped) {
			
			//get input object
			inputName = "maat_"+ itemDimensionSize;
			var input = $(":input[name = '"+ inputName +"']");
			// get div objects
			var divInput = document.getElementById("input_"+ itemDimensionSize);
			var divPlusMinus = document.getElementById("plusminus_"+ itemDimensionSize);
			var divLabel = document.getElementById("label_"+ itemDimensionSize);
						
			if (stock <= 10) {
				// set value to 0
				input.attr("value", "");
				// hide divs
				divInput.className = divInput.className + " input-field-hidden";
				divPlusMinus.className = divPlusMinus.className + " plusminus-hidden";
				divLabel.className = divLabel.className + " label-hidden";
			} else {
				// set value to besteleenheid
 				besteleenheidInt = parseInt(document.bestelformulier.besteleenheid.value);
				// disabled - this was annoying
				/*
				if (besteleenheidInt == 3) {
					input.attr("value", besteleenheidInt);
				}
				*/
				// show all divs
 				divInput.className = "input-field";
				divPlusMinus.className = "plusminus";
				divLabel.className = "label";
			}
					
		}
				
	}
		
}


function AddQuantity(artikel_id, objImage) 
{
	changeQuantity(artikel_id, objImage, "add");
}

function SubtractQuantity(artikel_id, objImage) 
{
	changeQuantity(artikel_id, objImage, "subtract");
}

function DeleteQuantity(artikel_id, objImage) 
{
	changeQuantity(artikel_id, objImage, "delete");
}


function changeQuantity(artikel_id, objImage, mode)
{
	var besteleenheid = getBestelEenheid(objImage);
	
	var input_name = artikel_id;
	
	// Note: because artikel_id contains a dot a selector like $("input#artikel_" + artikel_id) will not work
	var input = $(":input[name = '"+ input_name +"']");
	var value = input.attr("value") * 1;
	
	// Correct value for besteleenheid
	//CorrectQuantityForBestelEenheid(value, besteleenheid)
	
	if (mode == "add")
	{
		if (value + besteleenheid > 0) {
			input.attr("value", value + besteleenheid);
		} else {
			input.attr("value", besteleenheid);
		}
	}
	else if (mode == "subtract")
	{
		if (value - besteleenheid > 0) {
			input.attr("value", value - besteleenheid);
		} else {
			input.attr("value", 0);
		}
	}
	else if (mode == "delete")
	{
		input.attr("value", "");
	}
	
	if (isIpad==false) {
		input.focus();
	}
	if (isIpad==true) {
		UpdateTotaalAantal();
	}	

}

function getBestelEenheid(objImage)
{
	var besteleenheid = 1;
	
	imageClassName = objImage.className;
	besteleenheidString = imageClassName.substring(imageClassName.lastIndexOf("eenheid_")+8);
	if (besteleenheidString != '')	{
		besteleenheid = parseInt(besteleenheidString);
	}
	
	return besteleenheid;
}

function CorrectQuantityForBestelEenheid(quantity, besteleenheid)
{
	if ((quantity % besteleenheid) > 0) {
		quantity = besteleenheid;
	}
	
}


function doDivHover(objDiv, onOrOff)
{
	
	if (onOrOff == "on") {
		objDiv.style.border = "1px solid #000";
	} else if (onOrOff == "off") {
		objDiv.style.border = "1px solid #ccc";
	}
}

function doItemTextHover(positionNr, onOrOff)
{
	objLink = document.getElementById("link-"+ positionNr);

	if (onOrOff == "on") {
		objLink.className = "js-mouseover";
	} else if (onOrOff == "off") {
		objLink.className = "js-mouseout";
	}
	
}

function doImageHover(objImage, onOrOff)
{
	var mySource =  objImage.src;
	var extension = mySource.substring(mySource.lastIndexOf("."));
	
	if (onOrOff == "on")
	{
		currentSrc = objImage.src;
		currentSrc = currentSrc.replace(extension, '_hover'+ extension);
		objImage.src = currentSrc;
	} else if (onOrOff == "off") {
		currentSrc = objImage.src;
		currentSrc = currentSrc.replace('_hover'+ extension, extension);
		objImage.src = currentSrc;
	}
}


function setMainImageAndLink(mediaFile)
{
	objDivMainFrame = document.getElementById("mainframe");
	objDivMainFrame.style.background = "transparent url(/_generated/media/250/"+ mediaFile +") no-repeat scroll 50% 50%";

	objZoomLink = document.getElementById("single_2");
	currentLink = objZoomLink.href;
	objZoomLink.href = "/_generated/media/1000/"+ mediaFile;
	
}


function isValidOrderForm(objForm, deVolgendeVeldenText, geenKleurIngevoerdText, verkeerdeBesteleenheidText)
{
	var message = "";
	var colorValue = objForm.kleur.value;
	var besteleenheidValue = objForm.besteleenheid.value;

	if (colorValue == "") {
		message += "> "+ geenKleurIngevoerdText + "\n";
	}
	
	if ( (besteleenheidValue == "3") && (hasOneQuantityBelowMininum(objForm)) ) {
		message += "> "+ verkeerdeBesteleenheidText + "\n";
	}
	
	if (message != "")
	{
		message = deVolgendeVeldenText + ":\n\n" + message + "\n";
		alert(message);
		return false;
	} else {
		return true;
	}

}


function isValidWinkelwagenForm(objForm, verkeerdeBesteleenheidText)
{
	var isValidForm = true;
	var hasUnvalidQuantitiesInCart = false;
	
	for (i=0; i < objForm.elements.length; i++)
	{
		objElement = objForm.elements[i];
		elementName = objElement.name;
		if (elementName.indexOf("maat_") > -1) 
		{
			elementClass = objElement.className;
			if (elementClass == "per-drie")
			{
				myValue = objForm.elements[i].value;
				if (!isNaN(myValue)) {
					myValueInt = parseInt(myValue);
					if ((myValueInt % 3) > 0) {
						hasUnvalidQuantitiesInCart = true;
						objElement.className = elementClass + " invalidquantity";
					}
				}
			}
		}
	}
	
	if (hasUnvalidQuantitiesInCart) {
		isValidForm = false;
		alert(verkeerdeBesteleenheidText);
	}
	
	return isValidForm;
}

function isValidSearchForm(objForm, initialText)
{
	keywordValue = objForm.q.value;
	if ((keywordValue == "") || (keywordValue == initialText)) {
		return false;
	} else {
		return true;
	}
}


function hasOneQuantityBelowMininum(objForm)
{
	var myBoolean = false;

	for (i=0; i < objForm.elements.length; i++)
	{
		elementName = objForm.elements[i].name;
		if (elementName.indexOf("maat_") > -1) 
		{
			myValue = objForm.elements[i].value;
			if (!isNaN(myValue)) {
				myValueInt = parseInt(myValue);
				if ((myValueInt % 3) > 0) {
					myBoolean = true;
				}
			}
		}
	}
	
	return myBoolean;
}



function removeInitialText(objInput)
{
	objInput.value = "";
	objInput.style.color = "#000000";
}


function removeInitialTextNotEverything(objInput, intialText)
{
	if (objInput.value == intialText) {
		objInput.value = "";
	}
	objInput.style.color = "#000000";
}


function removeInitialTextBeforeSubmitting(initialText)
{
	objInput = document.getElementById("keyword")
	if (objInput.value == initialText)
	{
		objInput.value = "";
	}
}


function deleteFile(deleteUrl)
{
	if (confirm("Weet u zeker dat u dit bestand wilt verwijderen?")) {
		
		window.location.href = deleteUrl;
		
	} else {
		// do nothing
	}
}

function confirmLeegmaken(confirmText, deleteUrl)
{
	if (confirm(confirmText)) {
		
		window.location.href = deleteUrl;
		
	} else {
		// do nothing
	}
}


function confirmUrl(confirmText, newUrl)
{
	if (confirm(confirmText)) {
		
		window.location.href = newUrl;
		
	} else {
		// do nothing
	}
}



function insertMediaIdSetPreviewAndCloseFancyBox(MediaGuid, MediaId)
{
	// set input value
	objForm = parent.document.getElementById('CMS_SAV_FotoBoekItems');
	objForm.ID0ECCA_MediaId.value = MediaId;
	
	//show preview 
	parent.$("#mediaPreviewBox").slideDown();
	
	//set image
	imagePath = "/_generated/media/70/"+ MediaGuid + ".jpg";
	objImage = parent.document.getElementById('mediaPreviewImage');
	objImage.src = imagePath;
	
	//close
	parent.$.fn.fancybox.close();

}
