var URL					= "http://www.non-stopdogwear.no/index.php/";
var urlAppendJson 		= "nodesign/content/view/full/";
var urlAppendForhandler = "nsdw_utvikling/content/view/full/";

jQuery(document).ready(function() {
	
	/***** Reloads the basket when the quantity of an item is changed *****/
	$(".item-quantity").change(function() {
		var $form = $("#basket-form");
		var url   = $form.attr( 'action' );
		$form.find('input[name=StoreChangesButton]').trigger('click');
	}); 
	
	/***** Sends user to 'my page' when clicking 'continue shopping' *****/
	$("#continue-shopping-button").click(function(event) {
		event.preventDefault();
		var url = $("#my-page-link").attr("value");
		window.location.replace(url);
	});
	
	/***** Adds products to the basket with ajax-call (done to avoid sending user to basket when adding items) *****/
	 $(".buy-button .buy-form").submit(function(event) {
	 	
	 	/* stop form from submitting normally */
    	event.preventDefault();
    	
    	/* get some values from elements on the page: */
    	var $form = $( this ),
        	ContentNodeID 	= $form.find( 'input[name="ContentNodeID"]' ).val(),
        	ContentObjectID = $form.find( 'input[name="ContentObjectID"]' ).val(),
        	Quantity 		= $form.find( 'input[name="Quantity"]' ).val(),
        	url 			= $form.attr( 'action' );
		
		/* Send the data using post */
	    $.post( url, { ContentNodeID : ContentNodeID,
	    			   ContentObjectID : ContentObjectID,
	    			   Quantity : Quantity,
	    			   ActionAddToBasket : "" },
	    	function() {
	    		/* Reloads page */
	    		location.reload();
	    	}
	    );
	 });
	 
	 /* Sets every qty input fields to 1 (done to avoid a strange bug) */
		$(".buy-button .buy-form").each(function() {
			$(this).find( 'input[name="Quantity"]' ).val("1");
		});
	
	/***** Rounding corners on divs *****/
	// jQuery("#my-page div.rounded-corners").corner("6px");
	
	$("input.cancel-button").click(function() {
		$(".ezcc-forhandler").attr("disabled", true);
	});
	
	/***** Setting the buttons for changing user info *****/
	$(".ezcc-forhandler").attr("disabled", true);
	
	$("#change-email").click(function(){
		$(".ezcca-forhandler_epost").attr("disabled", false).focus();
	});
	$("#change-address").click(function(){
		$(".ezcca-forhandler_adresse").attr("disabled", false).focus();
	});
	$("#change-zipcode").click(function(){
		$(".ezcca-forhandler_postnummer").attr("disabled", false).focus();
	});
	$("#change-city").click(function(){
		$(".ezcca-forhandler_poststed").attr("disabled", false).focus();
	});
	$("#change-phone").click(function(){
		$(".ezcca-forhandler_telefon").attr("disabled", false).focus();
	});
	$("#change-website").click(function(){
		$(".ezcca-forhandler_nettside").attr("disabled", false).focus();
	});
	$("#change-contact-person-first-name").click(function(){
		$(".ezcca-forhandler_contact_person_first_name").attr("disabled", false).focus();
	});
	$("#change-contact-person-last-name").click(function(){
		$(".ezcca-forhandler_contact_person_last_name").attr("disabled", false).focus();
	});
	
	/***** Setting the cancel button, for editing user *****/
	$(".edit-user-small .cancel-button").click(function(){
		$(".edit-user-small .text-field").attr("disabled", true);
	});
	
	/***** Showing/hiding the login div *****/
	jQuery("a.login").toggle(
	  function () {
		jQuery("#login").slideToggle("fast");
		jQuery("a.login").addClass("login-active");
	  },
	  function () {
		jQuery("#login").slideToggle("fast");
		jQuery("a.login").removeClass("login-active");
	  }
	);
	
	jQuery("#login_close").click(function(){
		jQuery("#login").slideToggle("fast");
	});
	
	/***** Showing/hiding the additional info div, and info when item is out of stock,
	 	   on products for logged in users *****/
	/* Setting id's on divs: */
	$(".product-show-additional-info").each(function(index) {
		$(this).attr("id", "product-show-additional-info" + index);
	});
	$(".product-additional-info").each(function(index) {
		$(this).attr("id", "product-additional-info" + index);
	});
	
	/* Setting the toggle's */
	$(".product-show-additional-info").each(function(index) {
		$("#product-show-additional-info" + index).click(function() {
			$("#product-additional-info" + index).toggle("fast");
		});
	});
	
	/* Setting id's on divs: */
	$(".not-in-stock-info-button").each(function(index) {
		$(this).attr("id", "not-in-stock-info-button" + index);
	});
	$(".not-in-stock-info").each(function(index) {
		$(this).attr("id", "not-in-stock-info" + index);
	});
	
	/* Setting the toggle's */
	$(".not-in-stock-info-button").each(function(index) {
		$("#not-in-stock-info-button" + index).click(function() {
			$("#not-in-stock-info" + index).toggle("fast");
		});
	});

	/***** Toggling the div showing info on user edit *****/
	$("#cannot-change-info-button").click(function() {
		$("#cannot-change-info").toggle("fast");
	});
	
	$("#not-in-stock-info-button").click(function() {
		$("#not-in-stock-info").toggle("fast");
	});
	
	/***** Slider for header images *****/
	$("#slider_header").easySlider({
		auto: true, 
		continuous: true,
		controlsShow: false
    });
	
	/***** Slider for the product view. One slider-item is one product category *****/
	$("#slider_products").easySlider_products({
		auto: false,
		continuous: false,
		numeric: true,
		controlsShow: true,
		nextText: '',
		prevText: '',
		speed: 1,
		numericId: 'products-controls'
	});
	
	/***** Fjerner bilder fra de nyhetene som alltid ligger til venstre i siden *****/
	jQuery("#newsCont .attribute-image img").css("display","none");
	
	/* ----------------------------- START FINNE FORHANDLERE ----------------------------- */
	
	/***** Translating strings: *****/
	var currentURL = document.location.href;
	var searching, result, dealersFound, linkWebpage; 
	// English:
	if (currentURL.indexOf("index.php/eng") != -1) {
		searching 		= "Searching...";
		result 			= "Result:";
		dealersFound 	= "dealers found";
		linkWebpage		= "Link to webpage";	
	}
	// Not english: 
	else {
		searching 		= "Søker...";
		result 			= "Resultat:";
		dealersFound 	= "forhandlere funnet";
		linkWebpage		= "Link til nettside";
	}
	/********************************/
	
	// Henter inn fylker fra valgt land, vha ajax. 
	jQuery("#ddLand").change( function(){	
		var selectedValue = jQuery(this).val();
		
		// 0 = teksten "Velg land..."
		if (selectedValue != 0) {
			var current;
			var listFylker = jQuery("#ddFylke");
			// Requester json-formaterte fylker
			$.post(URL+urlAppendJson+escape(selectedValue), function(data) { 
				
				listFylker.empty();
				
				for (var key in data.content) {
					current = data.content[key];
					var fylke = document.createElement('option');
					fylke.text = current.name;
					fylke.value = current.value;
					try {
						document.getElementById('ddFylke').add(fylke, null);
					}
					catch(e) {
						document.getElementById('ddFylke').add(fylke); // IE only
					}
				}	
			}, "json");
		}
	});
	
	//Henter inn eventuelle forhandlere for valgt fylke, vha ajax
	jQuery("#btn_finn_forhandler").click( function() {
		
		document.getElementById('divForhandlerResult').innerHTML = '<span class="smallText">' + searching + '</span>';
		
		var selectedValue = jQuery("#ddFylke").val();
		
		// Requester json-formaterte forhandlere
		$.post(URL+urlAppendJson+escape(selectedValue), function(data) { 
			
			// JSON-object - forhandler
			var current;
			
			// Inneholder info + html tags for visning av info, hvis infoen finnes. Hvis info mangler er variabelen tom ("").
			var navn, adresse, postnr, poststed, telefon, epost, nettside;
			
			var antForhandlere = 0;
			var tempForhandler = "<ul>";
			
			if (data.content != null) {
				// For hver forhandler
				for (var key in data.content) {
					current = data.content[key];
					// if (current.vis == true) {
						antForhandlere++;
						// Hvis info mangler (eks tlf), vises ikke denne
						navn = '<span class="uppercase"><a onClick="showDealer(\' '+ URL+urlAppendJson+current.value +' \')">' 
								+current.name+ '</a></span><br />';
						if (isEmpty(current.adresse)) { adresse = '' }
							else { adresse = '<span class="adresse">'+current.adresse+'</span><br />' }
						if (isEmpty(current.postnr)) { postnr = '' }	
							else { postnr = '<span class="postnr">'+current.postnr+'</span>'}
						if (isEmpty(current.poststed)) { poststed = '' }
							else { poststed = ' <span class="uppercase">'+current.poststed+'</span><br />' }
						if (isEmpty(current.telefon)) { telefon = '' }
							else { telefon = '<span class="tlf">'+current.telefon+'</span><br />' }
						if (isEmpty(current.epost)) { epost = '' }
							else { epost = '<span class="epost"><a href="mailto:'+current.epost+'">'+current.epost+'</span><br />' }
						if (isEmpty(current.nettside)) { nettside = '' }
							else { nettside = '<span class="nettside"><a href="'+current.nettside+'" target="_blank">' + linkWebpage + '</a></span><br />'}
						
						tempForhandler += '<li><div class="forhandlerList">'
								   +navn
								   +adresse
								   +postnr
								   +poststed
								   +telefon
								   +epost
								   +nettside+'</div></li>'; //<div class="forhandlerKart">Kart</div></li>';
					// }
				}
			}
			var forhandler = "<h3>" + result + "</h3><br /><h4>" + antForhandlere + " " + dealersFound + "</h4>";
			forhandler += tempForhandler;
			
			
			document.getElementById('divForhandlerResult').innerHTML = forhandler;
			forhandler += "</ul>";
				
		}, "json");
	});
	
	
	
	/* ----------------------------- SLUTT FINNE FORHANDLERE ----------------------------- */
	
	/* Image map hilighter - Highlighst countries on the map, under dealers */
	/* Settings: */	
	$.fn.maphilight.defaults = {
		fill: true,
		fillColor: '000000',
		fillOpacity: 0.2,
		stroke: false,
		strokeColor: 'ff0000',
		strokeOpacity: 1,
		strokeWidth: 1,
		fade: true,
		alwaysOn: false,
		neverOn: false,
		groupBy: false
	}
	/* Sets the highlighting */
	$(".map").maphilight();
		
});

/* Outputs full view of dealer */
function showDealer( url ) {
	$.post(url, function(data) { 
		var forhandler ='<h2>' +data.name+ '</h2>'
						+'<p>' +data.beskrivelse+ '</p>'
						+'<p>' +data.adresse+ '<br />'
						+ data.postnr + ' <span class="uppercase">' +data.poststed+ '</span><br /></p>'
						+ '<p> <span class="bold">TLF:</span> ' +data.telefon+ '<br />'
						+ '<span class="bold">E-post:</span> <a href="mailto:' +data.epost+ '">' +data.epost+ '</a> <br />'
						+ '<span class="bold">Nettside:</span> <a href="' +data.nettside+ '" target="_blank">' +data.nettside+ '</a><br /></p>'
						+ '<p><span id="mapText" class="bold"></span>'
						+ '<div id="google-map" style="width: 500px; height: 280px;"></div></p>';
		document.getElementById('maincontent-design').innerHTML = forhandler;

		// If we have a map location, output the map
		if (! isEmpty(data.latitude) && ! isEmpty(data.longitude)) { 
			eZGmapLocation_MapView( data.latitude, data.longitude );
		}
	
	}, 'json');
}

function isEmpty(info) {
	if (info == "") {
		return true;
	}
	return false;
}

function eZGmapLocation_MapView( latitude, longitude )
{
	var zoommax = 13;
	
	document.getElementById('mapText').innerHTML += 'Kart: ';
	if( latitude && longitude )
	{
		var startPoint = new google.maps.LatLng( latitude, longitude );
		var zoom = zoommax;
		
	}
  else
  {
      var startPoint = new google.maps.LatLng( 0, 0 );
      var zoom = 0;
  }

  	var map = new google.maps.Map( document.getElementById( 'google-map' ), { center: startPoint, zoom : zoom, mapTypeId: google.maps.MapTypeId.ROADMAP } );
	var marker = new google.maps.Marker({ map: map, position: startPoint });
}
