HVEIM = {
	autoScroll: true,
	recipe_id: null,
	user_id: null
}

var prnd = Math.random() + ""; 
var pageid = prnd * 1000000000000; 

$(document).ready(function(){

	$("#Navigation li:last").css({border:'0px'});
	
	$("#TopNav a.login").click(function(){
		$("#TopLogin").toggle();
		return false;
	});
	
	style_fixes();
	init_login();
	
	$("div.Box div.Content").append("<div style='clear: both;'></div>");

	$("a.popup").click(function(){
		openPopup({
			"url":$(this).attr('href'),
			"clickToClose":true
		});
		return false;
	});
	
	$("a.favourite").click(function(){
		if ($(this).parent().hasClass('favourite'))
			$.get($(this).attr('href'),null,favourited);
		else if ($(this).parent().hasClass('favourited'))
			$.get($(this).attr('href'),null,unfavourited);
		else
			$.get($(this).attr('href'));
		return false;
	});
	
	$("a.print").click(function(){
		return false;
	});
	
	/* Coupon */
	$("#CouponList div.Coupon ul.Buttons li.select input[type='button']").click(function(){
	
		cb = $(this).siblings("input[type='checkbox']");
		$parents = $(this).parents('div.Coupon');
		if (cb.attr('checked'))
		{
			$parents.removeClass('Selected');
			cb.attr('checked',false);
		}
		else
		{
			$parents.addClass('Selected');
			cb.attr('checked',true);
		}
	});
	$("#CouponList .print a").click(function(){
		if ($("#CouponList div.Coupon ul.Buttons li.select input:checked").size() < 1)
			alert("Ekkert tilboð er valið. Til að prenta út tilboð þarf fyrst að velja þau tilboð sem á að prenta út.");
		else
			$("#CouponList form").submit();
	});
	$("#CouponList a").click(function(){
		return false;
	});
	
	$("#CouponList div.Coupon ul.Buttons li.email input[type='button']").click(function(){
		thiscb = $(this).parent().parent().find("li.select input[type='checkbox']");
		if (!thiscb.attr('checked'))
		{
			thiscb.attr('checked',true);
			thiscb.parents('div.Coupon').addClass("Selected");
		}
		coupons = [];
		$("#CouponList div.Coupon ul.Buttons li.select input[type='checkbox']:checked").each(function(){
			coupons.push($(this).val());
		});
		openPopup({
			"url": $(this).attr('href'),
			"data": {
				"coupons": serialize(coupons)
			},
			"clickToClose": true
		});
		
	});
	
	if ($("#CouponList").size() > 0)
	{
		
		$(".email a.email").click(function(){
			
			var cbs = $("#CouponList div.Coupon ul.Buttons li.select input[type='checkbox']:checked");
			if (cbs.size() < 1) {
				alert("Ekkert tilboð er valið. Til að senda tilboð þarf fyrst að velja þau tilboð sem á að senda.");
			}
			else {
				coupons = [];
				cbs.each(function(){
					coupons.push($(this).val());
				});
				openPopup({
					"url": $(this).attr('href'),
					"data": {
						"coupons": serialize(coupons)
					},
					"clickToClose": true
				});
			}
		});
		
		
	}
	
	/* Search box */
	/* deprecated
	if ($("#Header").css('height') == '290px')
	{
		$("#TopSearch").show();
	}
	*/
	
	/* Advice */
	
	$("div.Pager div.Print a.print").click(function(){
		window.location = $(this).attr('href');
	});
	$("#AdviceSend").click(function(){
		openPopup({
			"url":$(this).attr('href'),
			"width":400,
			"height":360,
			"clickToClose":true
		});
		return false;
	});

	/* Coupons */
	$("div.Coupon a.mail").click(function(){
		openPopup({
			"url":$(this).attr('href'),
			"width":400,
			"height":250,
			"clickToClose":true
		});
		return false;
	});
	
	if ($("#CouponList").size() > 0)
	{
		$("div.Pager a.print").unbind('click');
		$("div.Pager a.print").click(function(){
			$("#CouponPrint").submit();
			return false;
		});
	}
	

	/* Profile */
	if ($("#birthdate").size() > 0) {
		defaultDate = new Date();
		defaultDate.setFullYear(1970,0,1);
		$("#birthdate").datepicker({
			altField: '#birthdate',
			altFormat: 'dd.mm.yy',
			changeMonth: true,
			changeYear: true,
			defaultDate: defaultDate,
			yearRange: '1900:' + new Date().getFullYear()
		});
	}
	
	$("#Inventory .print a").click(function(){
		$("#InventoryForm").submit();
	});
	
	
	/* Recipes */
	if ($("#Recipe").size() > 0)
	{
		
		$("#Recipe div.Footer li.email a").click(function(){
			$("#RecipeEmail").dialog('open');
			return false;
		});
		$("#Recipe div.Footer li.list a").click(function(){
			$("#RecipeList").dialog('open');
			return false;
		});


		$("#RecipeEmail").dialog({autoOpen:false});
		$("#RecipeList").dialog({autoOpen:false});

		recipe_wine_init();
	
	/* Recipes > Rating */
		if( jQuery.ui )
		{
			var RatingValue = 0;
			var stepWidth = 12.5;
			$("#Recipe .RatingSystem .RatingHolder").mousemove(function(e){
				var x = e.pageX - $(this).offset().left;
				var steps = Math.floor(x/12.5) + 1;
				if(x < 6) steps = 0;
				$(this).children().css({width: stepWidth*steps }).css('background-image', 'url(/img/recipe_rating_big_half.png)');
			}).mouseout(function(){
				$(this).children().css({width: stepWidth*RatingValue }).css('background-image', 'url(/img/recipe_rating_big_full.png)');
			}).click(function(e){
				var x = e.pageX - $(this).offset().left;
				var steps = Math.floor(x/12.5) + 1;
				if(x < 6) steps = 0;
				RatingValue = steps;
				$(this).prev("input").val(RatingValue/2);
				$(this).children().css({width: stepWidth*steps });
			}).css('cursor', 'pointer'); // IE6 fix, for pointer cursor.
			
			
			/* Recipies > Amount slider */
				$(".IngredientCalc").each(function(){
					var ingredientValue = $(this).text();
					$(this).attr('value', ingredientValue / 4);
				});
				$("#Recipe .Amount .Slider").slider({
					value: 4,
					min: 1,
					max: 10,
					step: 1,
					slide: function(event, ui){
						changeIngredientsValues(ui.value);
					}
				});
				$("#AmountValue").text($("#Recipe .Amount .Slider").slider("value"));
				if( $.cookie('ingredientsMultiplier') != null )
				{
					$("#Recipe .Amount .Slider").slider("value", $.cookie('ingredientsMultiplier') );
					changeIngredientsValues( $.cookie('ingredientsMultiplier') );
				}else{
					changeIngredientsValues( $("#Recipe .Amount .Slider").slider("value") );
				}
			if (!HVEIM.user_id)
			{
				$("#RatingSubmit").click(function(){
					popup_notloggedin();
					return false;
				});
			}
		}
		$("a.SubmitImage").click(function(){
			openPopup({
				"url":$(this).attr('href'),
				"width":400,
				"height":280,
				"clickToClose":true
			});
			return false;
		});
		
		
	}
	
	/* Recipes categories */
	$("#RecipeCategoryList li ul").hide();
	$("#RecipeCategoryList li a").click(function(){
		if ($(this).parent().children("ul:hidden").size() > 0) {
			$(this).parent().parent().children('li').children("ul").slideUp();
			$(this).parent().children("ul").slideUp();
			$(this).parent().children("ul:hidden").slideDown();
			if ($(this).attr('href') == "#")
				return false;
		}
	});
	$("#RecipeCategoryList li a.selected").each(function(){
		$(this).parents('ul').show();
		$(this).parent().children("ul").show();
	});


	/* Valid user buttons */
	if (HVEIM.user_id == null) {
		$(".validuser").unbind('click').click(function(){
			popup_notloggedin();
			return false;
		});
	}


	/* allow href buttons to work */
	$("input[href].href").click(function(){
		window.location = $(this).attr('href');
	});
	
});


function init_login()
{
	$("#TopLogin form").submit(function(){
		toplogin_login();
		return false;
	});

	$("#TopLogin input[type='image']").click(function(){
		toplogin_login();
		return false;
	});	
}

function toplogin_submit()
{
	return false;	
}

function toplogin_login()
{
	$.post($("#TopLogin form").attr('action'),{email:$("#TopLogin input[name='email']").val(),password:$("#TopLogin input[name='password']").val()},
	function(data){if (data) {
		$("#TopLogin").html(data);
		init_login();
	}else{
		window.location.reload(true);
	}});
}


//centering popup
function centerPopup()
{
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popupWindow").height();
	var popupWidth = $("#popupWindow").width();
	//centering
	$("#popupWindow").css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2 + $(window).scrollTop(),
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	
	$("#popupBackground").css({
		"height": windowHeight,
		"width": windowWidth
	});
}

function openPopup(object)
{
	if (!object.data) object.data = {};
	if (!object.func)
	{
		object.func = popup_addClose;
	}
	if (!object.width)
	{
		object.width = 408;
	}
	if (object.width)
	{
		$("#popupWindow").css({"width":object.width});
	}
	if (object.height)
	{
		$("#popupWindow").css({"height":object.height});
	}
	$("#popupBackground").show();
	$("#popupWindow").fadeIn();
	centerPopup();
	$("#popupWindow").load(object.url,object.data,object.func);
	$(window).scroll(centerPopup);
	if (object.clickToClose)
	{
		$("#popupBackground").click(closePopup);
	}
	
}
function popup_addClose()
{
	$("#popupWindow").append(jQuery("<img src='/img/popup_x.png' style='position:absolute;top:5px;right:5px;cursor:pointer;'>").click(closePopup));
}

function popup_notloggedin()
{
	openPopup({
		"url":WEB_ROOT+"/profile/notloggedin",
		"width":280,
		"height":200,
		"clickToClose":true
	});
}



function closePopup()
{
	$("#popupBackground").hide();
	$("#popupWindow").fadeOut(500,function(){$(this).html('')});
	$("#popupBackground").unbind('click',closePopup);
	$(window).unbind('scroll',centerPopup);
}

function favourited()
{
	url = $('a.favourite').attr('href');
	althref = $('a.favourite').attr('althref');
	$("a.favourite").parent().addClass('favourited').removeClass('favourite').children("a.favourite").html('Taka úr uppáhald').attr('href',althref).attr('althref',href);
}
function unfavourited()
{
	url = $('a.favourite').attr('href');
	althref = $('a.favourite').attr('althref');
	$("a.favourite").parent().addClass('favourite').removeClass('favourited').children("a.favourite").html('Setja í uppáhald').attr('href',althref).attr('althref',href);
}

function recipe_wine_init()
{
	$("div.WineSmall div.WinePaging a").click(function(){
		$("div.WineSmall").load($(this).attr('href'),null,recipe_wine_init);
		return false;
	});
	
	$("div.WineSmall img.WineImage").hover(function(){
		if ($("#wine_large").attr('loaded') != 'true')
		{
			$("div.WineBig").load($("#wine_large").val());
			$("#wine_large").attr('loaded','true');
		}
		$("div.WineBig").show().css({zIndex: 10});
		
		},function(){$("div.WineBig").hide();});
	
}

function changeIngredientsValues( $multiplier )
{
	$.cookie('ingredientsMultiplier', $multiplier, { path: '/', expires: 7 }); // 7 dagar = 1 vika
	$("#AmountValue").text($multiplier);
	$(".IngredientCalc").each(function(){
		var ingredientValue = $(this).attr('value');
		$(this).text( formatDecimals( ingredientValue * $multiplier ) );
	});
	/*
	var pUrl = ($("#Recipe .print a").attr("href"));
	pUrl = pUrl.split("/").reverse();
	pUrl[0] = $multiplier;
	$("#Recipe .print a").attr("href", pUrl.reverse().join('/'));
	*/
}

function formatDecimals( val )
{
	var $dec = val - Math.floor(val);
	var $add = 0;
	var $append = '';
	
	if( $dec >= 0.20 && $dec <= 0.36)
		$append = '¼';
	else if ($dec >= 0.37 && $dec <= 0.64 )
		$append = '½';
	else if ( $dec >= 0.65 && $dec <= 0.90 )
		$append = '¾';
	else if( $dec > 0.90 && $dec <= 0.99 )
		$add = 1;
	else if ($dec == 0) $apprent = '';
	else $append = $dec;
	
	if( (Math.floor(val) + $add) > 0 )
		val = (Math.floor(val) + $add) + " " + $append;
	else
		val = $append;
	
	return val;
}

function style_fixes()
{
	$("div.RecipeItem").parent().each(function(){
		$(this).children("div.RecipeItem:last").css("border-bottom","0").css("margin-bottom","0");
	});
}

function serialize (mixed_value) {
    // Returns a string representation of variable (which can later be unserialized)  
    // 
    // version: 910.813
    // discuss at: http://phpjs.org/functions/serialize
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
    // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
    // +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
    // +      input by: Martin (http://www.erlenwiese.de/)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
    var _getType = function (inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            mixed_value = this.utf8_encode(mixed_value);
            val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += this.serialize(okey) +
                        this.serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
            val = "N";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }
    return val;
}

function utf8_encode ( argString ) {
    // Encodes an ISO-8859-1 string to UTF-8  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/utf8_encode
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
 
    var utftext = "";
    var start, end;
    var stringl = 0;
 
    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
 
        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }
 
    if (end > start) {
        utftext += string.substring(start, string.length);
    }
 
    return utftext;
}