﻿$(document).ready(function(){
	$(document).pngFix();
	
	// All input fields assigned with the class 'default' will
	// get their default values hidden when clicked, and reset again
	// if the user leaves the field empty or hasnt changed anything
	// The searchfields needs an accompanying hidden input with the
	// same id but suffixed "-default" that contains the default value.
	$("input.default, textarea.default").each(function() {
		var defaultVal = $(this).next(".defaultvalue").val();
		if (!$(this).val())
			$(this).val(defaultVal);
		$(this).focus(function() {
			if ($(this).val() == defaultVal)
				$(this).val("");
		});
		$(this).blur(function() {
			if ($(this).val() == "")
				$(this).val(defaultVal);
				
			if($(this).attr("id") == "form-social") {
				if(!validatePNum($(this).val())) { 
					var error_element = "<p style='font-size: 11px; color: #800000; position: absolute; top: -2px; right: -220px; display: block; width: 200px;'>";
					error_element += "'" + $(this).val() + "' är inte ett korrekt personnummer. Skriv i formatet: 197201232741.</p>";
					$(this).parent().css("position", "relative");
					$(this).parent().append(error_element);
					$(this).val('');
				}
			}
		});
	});
	
	$(".validate").click(function() {
		var parentObj = $(".form");
		var validated = true;
				
		$(parentObj).find(".required").each(function() {
			
			if($(this).val() == "" || $(this).val() == $(this).next(".defaultvalue").val()) {
				$(this).addClass("has-error");	
				validated = false;
			}
		});

		if (!validated) {
			$("p.error").show();
			return false;
		}
		else if (validated) {
			$("p.error").hide();				
			$("#contactform").submit();	
		}
	});

	// Clear error when correcting it
	$(".required")
	.keydown(function() {
		if($(this).hasClass("has-error"))
			clearError($(this));
	});
	
	// Trigger the search function when using the ENTER key
	$("#site-search-input").keydown(function(e) {
		if (e.keyCode == 13) {
			var valobj = $(this).siblings("#site-search-submit");
			submitsearch($(valobj));
			return false;
		}
	});
	
	// Top search
	$("#site-search-submit")
	.click(function() {
		if($("#site-search").hasClass("expanded")) {
			submitsearch($(this));
		}
		else {
			$("#site-search").animate(
				{ width: 167 },
				{ queue: false, duration: 200,
					complete: function() {
						$("#site-search").addClass("expanded");
					}
				}
			);
			$("#site-search-content").addClass("active");
		}
		return false;
	});
	
	$("#site-search-input").blur(function() {
		if($("#site-search").hasClass("expanded")) {
			$("#site-search").animate(
				{ width: 29 },
				{ queue: false, duration: 200,
					complete: function() {
						$("#site-search").removeClass("expanded");
						$("#site-search-content").removeClass("active");
					}
				}
			);	
		}
	});
	
	$(".toggle").click(function() {
		$(this).closest(".richtext").find(".in-depth").slideToggle(200);
	});
	
	$("a.in-english").click(function() {
		// Create the dialog
		$("#lang-dialog").dialog({
			dialogClass: 'lang-dialog',
			modal: true,
			resizable: false,
			width: 600,
			close:function() {
				// Destroy the dialog-object when it is closed
				$(this).dialog("destroy");
			}
		});
		return false;
	});
	
	$("a.fancybox").fancybox({
		'autoScale': false,
		'width': 911,
		'height': 451,
		'type' : 'swf',
        'swf' : {
        	'wmode' : 'transparent',
            'flashvars' : 'xmlPath=flash/cil_data.xml'
     	} 
    });
	
	/*$("a.fancybox_spotify").fancybox({
		'autoScale': false,
		'width': 911,
		'height': 469,
		'type' : 'swf',
        'swf' : {
        	'wmode' : 'transparent'
     	} ,
		'onStart'		: function() {
			if(typeof(pageTracker) !== 'undefined'){
		    	pageTracker._trackPageview("/startpage-banner-click.html");
			}
		}
    });*/
	
	/*if($.getUrlVar('view_spotify')){
		$("a.fancybox_spotify").trigger('click');
	}*/
	
	if($.getUrlVar('view_quiz')){
		$("a.fancybox").trigger('click');
	}
});

function clearError(obj) {
	if (obj.val()) {
		obj.removeClass("has-error");
	}
}

function submitsearch(obj) {
	var url = $(obj).attr("href");
	url += url.indexOf("?") > -1 ? "&" : "?";
	url += "query=" + encodeURIComponent($(obj).siblings("input#site-search-input").val());
	document.location = url;
}

// Startpage animation
$(function() {
	$("#site-areas li")
	.mouseover(function() {
		$(this).stop();
		activate($(this).children(".area-content"));
		deactivate($(this).siblings("li").children(".area-content"));
	})
	.click(function() {
		var url = $(this).find("a").attr("href");
		document.location = url;
	});
	
	$("#site-areas ul")
	.mouseleave(function() {
		var obj = $("li .area-content");
		obj.stop();
		obj.children(".detail").fadeOut(500);
		obj.animate(
		{ height: 190, opacity: 1},
			{ queue: false, duration: 300,
				complete: function() {
					obj.removeClass("active");
				}
			}
		);	
	});
});

function activate(obj) {
	obj.children(".detail").fadeIn(500);
	obj.animate(
		{ height: 223, opacity: 1},
		{ queue: false, duration: 300,
			complete: function() {
				obj.addClass("active");
			}
		}
	);	
}

function deactivate(obj) {
	obj.children(".detail").fadeOut(500);
	obj.stop();
	obj.animate( 
		{ height: 190, opacity: 0.5},
		{ queue: false, duration: 300,
			complete: function() {
				obj.removeClass("active");
			}
		}
	);	
}


$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});


function validatePNum(sPNum)
{
  var numbers = sPNum.match(/^(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)$/);
  var checkSum = 0;

  var d = new Date();
  if (!isDate(sPNum.substring(0,4),sPNum.substring(4,6),sPNum.substring(6,8))) {
    return false;
  }

  if (numbers == null) { return false; }

  var n;
  for (var i = 3; i <= 12; i++)
  {
    n=parseInt(numbers[i]);
    if (i % 2 == 0) {
      checkSum+=n;
    } else {
      checkSum+=(n*2)%9+Math.floor(n/9)*9 
    }
  }

  if (checkSum%10==0) { return true;}
  return false;
}

function getYear(y) { return (y < 1000) ? y + 1900 : y; }

function isDate(year, month, day) 
{
  month = month - 1; // 0-11 in JavaScript
  var tmpDate = new Date(year,month,day);
  if ( (getYear(tmpDate.getYear()) == year) &&
  (month == tmpDate.getMonth()) &&
  (day == tmpDate.getDate()) )
    return true;
  else
    return false;
}

