var heroInterval = false;

$(document).ready(function() {

	// ===== MAIN NAV =====

	// Add span to main nav links
	$(this).find("nav#nav-main > ul > li > a").each(function() { 
		linkText = $(this).html();
		$(this).html('<span>' + linkText + '</span>');
	});

	// Blur button on click
	$("nav#nav-main > ul > li > a").click(function() {
		this.blur();
	});

	// HoverIntent to main nav links
	var config_hoverIntent = {    
		over: nav_show, 
		out: nav_hide,
		timeout: 500
	};
	$("nav#nav-main > ul > li").hoverIntent(config_hoverIntent);
	
	// show subnav panel
	$("nav#nav-main > ul > li").bind("mouseenter", function () {

		// hide other panels at once - but not this one if it is already selected
		$("nav > ul > li.hover").not($(this)).removeClass("hover");
		$("nav > ul > li").not($(this)).find("ul.subnav").hide();
		
		// show the selected subnav panel
		nav_show();
	});

	// hide subnav panel 
	$("nav#nav-main > ul > li").bind("mouseleave", function () {
		nav_hide();
	});

	// ===== HERO =====

	// initialize hero slideshow
	slideshow_hero();

	// put link on entire hero element
	$(this).find(".hero-feature a").each(function() { 
		var theLink = $(this).attr("href");
		if (theLink) {
			var theHero = $(this).parent();
			theHero.click(function() {
				window.location = theLink;
			});
		}
	});
	
	// hero navigation buttons
	$("#nav-hero a").click(function() {
		theID = $(this).attr("id");
		theID = theID.replace("show-", "");
		
		$(".hero-feature").hide();
		$("#" + theID).fadeIn();
		
		$("#nav-hero a").removeClass("active");
		$(this).addClass("active");
		
		slideshow_hero();
		
		return false;
	});	
	
	// activate first hero nav button
	$("#nav-hero a").first().addClass("active");

	// ===== SPOTLIGHT =====
	
	// hide link and add it to the container
	$(this).find("p.spotlight-link a").each(function() { 
		var theLink = $(this).attr("href");
		
		if (theLink) {
		
			var theSpotlight = $(this).parent().parent();
		
			theSpotlight.click(function() {
				window.location = theLink;
			});
			
			theSpotlight.children("img").each(function() {
				$(this).wrap('<a href="' + theLink + '" />');
			});

			theSpotlight.mousedown(function() {
			   $(this).addClass("spotlight-click");
			});
			theSpotlight.mouseup(function() {
			   $(this).removeClass("spotlight-click");
			});
			theSpotlight.mouseover(function() {
				$(this).addClass("spotlight-hover");
			});
			theSpotlight.mouseout(function() {
				$(this).removeClass("spotlight-click");
				$(this).removeClass("spotlight-hover");
			});
			
		}
		
		$(this).parent().hide();
	});

	// set height to highest container
	$(this).find(".spotlight-row").each(function() {
		var theHeight = 0;
		$(this).find(".spotlight").each(function() {
			if ($(this).height() > theHeight) {
				theHeight = $(this).height();
			}
		});
		
		$(this).find(".spotlight").each(function() {
			$(this).height(theHeight);
		});
	});

	// ===== SOCIAL =====
	$("p#spotlight-social-facebook").click(function() {
		window.open("http://www.facebook.com/NextGenTel");
		return false;
	});
	$("p#spotlight-social-twitter").click(function() {
		window.open("http://twitter.com/NextGenTel");
		return false;
	});
	$("p#spotlight-social-blogg").click(function() {
		theLink = $("p#spotlight-social-blogg a#spotlight-social-blogg-link").attr("href");
		if (theLink) {
			window.open(theLink);
		} else {
			window.open("http://www.nextgentel.no/detneste/");
		}
		return false;
	});

	// ===== TABS =====
	
	// Add span to Tabs
	$(this).find("ul.tab-menu > li > a").each(function() { 
		linkText = $(this).html();
		$(this).html('<span>' + linkText + '</span>');
	});
	
	// Initialize Tabs
	$(".tabs").tabs();
	
	// Blur button on click
	$(".tabs > ul > li > a").click(function() {
		this.blur();
	});
	
	// ===== LAYOUT - min-height =====
	
	if ($("#sidebar").height() > $("#content").height()) {
		$("#content").css("min-height", $("#sidebar").height() + "px");
	}

	if ($("#nav-submenu").height() > $("#content").height()) {
		$("#content").css("min-height", $("#nav-submenu").height() + "px");
	}

	minHeight = $(window).height();
	minHeight -= $("footer").height();
	minHeight -= $("header").height();
	// minHeight -= $("nav").height();
	minHeight -= 155;
	
	$("#main").css("min-height", minHeight + "px");	

	$(".body-hero #main").css("min-height", minHeight - 100 + "px");	
	
	// ===== DATEPICKER =====
	$(".datepicker").datepicker();
	
	// ===== SIDEBAR LINK LISTS ====
	$(this).find("div#sidebar > div.box > ul > li").each(function() { 
		linkText = $(this).html();
		$(this).html('&ndash; ' + linkText);
	});
	
	// ===== DIALOG =====

	$(".ringmeg").click(function() {

		_gaq.push(['_trackEvent', 'Ring meg', 'Start', 'Ring meg - Start']);

		// Overlay
		$("body").append('<div id="body-overlay"></div>');
		$("#body-overlay").css("height", $("body").height());
		$("#body-overlay").fadeIn("slow");
		
		// Målgruppe
		theURL = "/privat/kontakt/kontaktmeg/";
		var erBedrift = false;
		if (location.href.search("/bedrift/") > -1) {
			theURL = "/bedrift/kontakt/kontaktmeg/";
			erBedrift = true;
		}
		
		// Build Dialog
		var theDiv = '<div class="dialog" id="dialog-ringmeg">';
		theDiv += '<a id="dialog-lukk" class="dialog-lukk" href="#" title="Lukk">x</a>';
		theDiv += '<h3>Ring meg</h3>';
		theDiv += '<p class="validateTips">Skriv inn ditt telefonnummer. <br> Vi ringer deg tilbake.</p>';
		theDiv += '<form method="get" action="' + theURL + '">';
		theDiv += '<fieldset>';
		theDiv += '<p>';
		theDiv += '<label for="ringmeg-telefon">Telefon</label>';
		theDiv += '<input type="text" name="mobil" id="ringmeg-telefon" />';
		theDiv += '</p>';
		theDiv += '<p>';
		theDiv += '<input class="submit" type="submit" name="dialog-submit" id="dialog-submit" value="OK" />';
		theDiv += '<a id="dialog-avbryt" class="dialog-lukk" href="#" title="Lukk">Avbryt</a>';
		theDiv += '</p>';
		theDiv += '</fieldset>';
		theDiv += '</form>';
		if (erBedrift) { 
			theDiv += '<p>Salg Bedrift ringer tilbake hverdager 0800 - 1600. For Kundeservice: Ring 07978 eller bruk <a href="https://www.nextgentel.com/kundesider/bedrift2/NAPkontakt.php" id="dialog-kontaktskjema">kontaktskjema</a>.</p>';
		} else {
			theDiv += '<p>Salgsavdelingen ringer tilbake hverdager 0830 - 1630. For Kundeservice: Ring 07979 eller bruk <a href="https://www.nextgentel.com/minside/kundeservice/kontaktskjema/" id="dialog-kontaktskjema">kontaktskjema</a>.</p>';
		}
		theDiv += '</div>';
		
		// Show Dialog
		$("body").append(theDiv);
		$("#dialog-ringmeg").css("left", $(window).width() / 2 - ($("#dialog-ringmeg").width() / 2));
		$("#dialog-ringmeg").css("top", $(window).height() / 2 - $("#dialog-ringmeg").height());
		$("#dialog-ringmeg").fadeIn("fast");
		$("#ringmeg-telefon").attr("autocomplete", "off").focus();

		$("#dialog-submit").click(function() {

			$(".dialog-feilmelding").remove();
			
			$.ajax({
				url: "/1res/inc/leads/leads-ringmeg.php",
				data: { mobil: $("#ringmeg-telefon").val(), ref: location.href },
				success: function(data) {
					if (data == 1) {

						_gaq.push(['_trackEvent', 'Ring meg', 'OK', 'Ring meg - OK']);
						_gaq.push(['_trackPageview', '/events/ringmeg'])

						$(".dialog").html('<a id="dialog-lukk" class="dialog-lukk" href="#" title="Lukk">x</a><h3>Takk for din henvendelse!</h3><p>Vi ringer deg tilbake p&aring; <strong>' + $("#ringmeg-telefon").val() + '</strong> <br />s&aring; snart som mulig.</p><p><a href="#" class="dialog-lukk">Lukk vinduet</a></p>')

						/*
						START Tracking Carat
						*/
						
						var axel = Math.random() + "";
						var a = axel * 10000000000000;
						var newIFrame = document.createElement('iframe');
						newIFrame.src = 'http://fls.doubleclick.net/activityi;src=3068060;type=leads302;cat=ringm190;ord=' + a + '?';
						newIFrame.width = "1";
						newIFrame.frameBorder = "0";
						newIFrame.height = "1";
						
						$("footer").before(newIFrame);
						
						/* 
						END Tracking Carat
						*/
						
						$(".dialog-lukk").click(function() {
							return lukkDialog();
						});
						
						setTimeout(function() { lukkDialog(); }, 2000);

					} else if (data == 3) {

						_gaq.push(['_trackEvent', 'Ring meg', 'Feil', 'Ring meg - Feil']);
						
						$("#dialog-ringmeg fieldset").append('<p class="dialog-feilmelding" id="ringmeg-feilmelding">Du har allerede bedt om &aring; bli oppringt.</p>');
						$("#ringmeg-telefon").focus();
												
					} else {

						_gaq.push(['_trackEvent', 'Ring meg', 'Feil', 'Ring meg - Feil']);
						
						$("#dialog-ringmeg fieldset").append('<p class="dialog-feilmelding" id="ringmeg-feilmelding">Det oppstod en feil. Oppgi ditt telefonnummer, 8 siffer.</p>');
						$("#ringmeg-telefon").focus();
						
					}
				}
			});
			return false;
		});

		$(".dialog-lukk").click(function() {
			return lukkDialog();
		});

		$(document).keydown(function(e) {
			if (e.keyCode == 27) {
				lukkDialog();
			}
		});
		
		return false;
	});
	
	function lukkDialog() {
		$(".dialog").remove();
		$("#body-overlay").fadeOut("fast", function() {
			$(this).remove();
		});
		return false;
	}
	
	// ===== CHAT =====
	
	$("#chat-salg-open").click(function() {
		window.open('http://www.nextgentel.no/ressurser/phplive/request.php?l=admin&x=1&deptid=1&page=' + location.href, 'salgschat', 'width=470, height=450'); 
		return false;
	});

	$("#chat-ks-open").click(function() {
		window.open('https://www.nextgentel.com/phplive/phplive.php', 'servicechat', 'width=700, height=500'); 
		return false;
	});

/*	$("#chat-ks-open-meny").click(function() {
		window.open('https://www.nextgentel.com/phplive/phplive.php', 'servicechat', 'width=700, height=500'); 
		return false;
	});*/
	
	// ===== FACEBOOK =====
	if ($("#fb-root").length > 0) {
		FB.init({ 
			appId: '194671503900833', cookie:true, 
			status: true, xfbml:true 
		});
	}
	
	// ===== LIKE & SHARE =====
	$("#likeshare-facebook").click(function() {
		shareURL = window.location;
		window.open("http://www.facebook.com/sharer.php?u=" + shareURL, "facebook", "width=550,height=350");
		return false;
	});

	$("#likeshare-twitter").click(function() {
		shareURL = window.location;
		shareText = $("title").html();
		window.open("http://twitter.com/share?text=" + shareText + "&url=" + shareURL, "twitter", "width=500,height=300");
		return false;
	});

	$("#likeshare-epost").click(function() {
		shareURL = window.location;
		shareText = $("title").html();
		window.open("/privat/tips/?text=" + shareText + "&url=" + shareURL, "epost", "width=550,height=500");
		return false;
	});

	$("#likeshare-print").click(function() {
		window.print();
		return false;
	});
	
	/*
	$("section#likeshare").click(function() {
		$("section#likeshare").css("margin-bottom", "170px");
	});
	*/
	
	// ===== CONTACT FORM ===== 
	
	$("form#kontakt input#submitknapp").addClass("disabled").attr("disabled", true);
	$("form#kontakt textarea").keyup(function() {
		if ($(this).val() != "") {
			$("form#kontakt input#submitknapp").removeClass("disabled").attr("disabled", false);
		}		
	});

	// ===== FORMS ===== 
	$("#content form input[type=text]").addClass("text");
	$("#content form input[type=password]").addClass("text");
	$("#content form input[type=tel]").addClass("text");
	$("#content form input[type=email]").addClass("text");
	$("#content form input[type=number]").addClass("text");
	$("#content form input[type=radio]").addClass("radio").parent().addClass("label_radio");
	$("#content form input[type=checkbox]").addClass("checkbox").parent().addClass("label_checkbox");
	$("#content form input[type=submit]").addClass("submit");
	
	$("#content form input:checked").parents("tr").addClass("checked");

	$("#content form:not(.no-tr-input) tbody tr").click(function() {
		
		if (!$("input", this).attr("disabled")) {
			$(this).siblings().removeClass("checked");
			$("input", this).attr("checked", "checked");
			$(this).addClass("checked");
		}
	});
	
	$("#content form legend").first().css("padding-top", "0");
	
	
	// ===== TV CHANNELS ===== 
	$(".tv-kanal").click(function() {
		
		var theID = $(this).attr("id").replace("tv-kanal-", "");
		var thePos = $(this).position();
		
		$("#tv-kanal-info").load("/1res/inc/produkt/privat/tv/ajax-kanal-boks.php?id=" + theID, function() {
			$("#tv-kanal-info").css("top", thePos.top + 30);
			$("#tv-kanal-info").css("left", thePos.left + 20);
			$("#tv-kanal-info").show();
		});
		
		return false;
	});

	$(".tv-kanal-grid").click(function() {
		
		var theID = $(this).attr("id").replace("tv-kanal-", "");
		var thePos = $(this).parent().position();
		
		$("#tv-kanal-info").load("/1res/inc/produkt/privat/tv/ajax-kanal-boks.php?id=" + theID, function() {
			$("#tv-kanal-info").css("top", thePos.top + 35);
			$("#tv-kanal-info").css("left", Math.min(660, thePos.left + 35) );
			$("#tv-kanal-info").show();
		});
		
		return false;
	});
	
	$("body").has("#tv-kanal-info").click(function() {
		$("#tv-kanal-info").hide();
	});

	// PLACEHOLDER FIX FAQ SEARCH
	$("input.search-header-text").focus(function() { 
		if($(this).val() == $(this).attr("placeholder")) {
			$(this).val('');
			$(this).removeClass("placeholder");
		}
	}).blur(function() { 
		if($(this).val() == '') {
			$(this).val($(this).attr("placeholder"));
			$(this).addClass("placeholder");
		} 
	}).blur();
	
	$("form#search-header").submit(function() {
		if ($("input.search-header-text").val() == $("input.search-header-text").attr("placeholder")) {
			$("input.search-header-text").val("")
		}
	});

	// EXTERNAL LINKS / NEW WINDOW
	externalLinks();
	trackExternalLinks();

});

// MAIN NAV FUNCTIONS

function nav_show() {
	$(this).addClass("hover");
	$(this).find(".subnav").stop().fadeTo(0, 0.90).show(); //Find sub and fade it in
}

function nav_hide() {
	$(this).removeClass("hover");
	$(this).find(".subnav").stop().fadeTo(200, 0, function() { //Fade to 0 opactiy
		$(this).hide();  //after fading, hide it
	});
}

// EXTERNAL LINK / NEW WINDOW

function externalLinks() {  
	if (!document.getElementsByTagName) return;  
	var anchors = document.getElementsByTagName("a");  
	for (var i=0; i<anchors.length; i++) {  
		var anchor = anchors[i];  
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")  
			anchor.target = "_blank";  
	}  
}

function trackExternalLinks() {
	$(".external_kredinor").click(function() {
		_gaq.push(['_trackEvent', 'External', 'Click', 'Kredinor']);
	});
}  

// HERO ANIMATION FUNCTIONS

// timer function for hero
function slideshow_hero() {
	
	if ($("div#hero-main div").length > 1) {
		clearInterval(heroInterval);
		heroInterval = setInterval("next_slide()", 7000);
	}
}

// display next slide
function next_slide() {

	var active = $("div#hero-main div:visible");
	var next = active.next().length ? active.next() : $("div#hero-main div:first");
	
	theID = next.attr("id");
	$(".hero-feature").hide();
	$("#" + theID).fadeIn("slow");

	$("#nav-hero a").removeClass("active");
	$("#show-" + theID).addClass("active");
	
}

// HOVERINTENT PLUGIN

/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

// DATEPICKER L18N

/* Norwegian initialisation for the jQuery UI date picker plugin. */
/* Written by Naimdjon Takhirov (naimdjon@gmail.com). */
jQuery(function($){
    $.datepicker.regional['no'] = {
		closeText: 'Lukk',
        prevText: '&laquo;Forrige',
		nextText: 'Neste&raquo;',
		currentText: 'I dag',
        monthNames: ['Januar','Februar','Mars','April','Mai','Juni',
        'Juli','August','September','Oktober','November','Desember'],
        monthNamesShort: ['Jan','Feb','Mar','Apr','Mai','Jun',
        'Jul','Aug','Sep','Okt','Nov','Des'],
		dayNamesShort: ['S&oslash;n','Man','Tir','Ons','Tor','Fre','L&oslash;r'],
		dayNames: ['S&oslash;ndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','L&oslash;rdag'],
		dayNamesMin: ['S&oslash;','Ma','Ti','On','To','Fr','L&oslash;'],
		weekHeader: 'Uke',
        dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional['no']);
});

/* DEBUG STUFF */

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}


