$(function() {
	$('#search-box, #search_again').originalValue();
	$('.tabcontainer').SimpleTabs();

	$("table").find(".Column0").parent().parent().parent().addClass("gradient");
	
	jQuery('#backPicker').jcarousel({});


	// Image Loop
	ImageLoopStart('#bigbackgrounds li');

	$('.moveEpgUpp').mousedown(function(){
   		$('.sEpgShows').css('margin-top', function(index) {
			var strMarginNow = $('.sEpgShows').css('margin-top').replace('px', '');
			var iMarginNow = parseInt(strMarginNow)
			var height = $('.sEpgShows').height();
			if (iMarginNow < -50)
				return iMarginNow + 50 + 'px';
			else
				return '0px';
		});
	});
	$('.moveEpgDwn').mousedown(function(){
   		$('.sEpgShows').css('margin-top', function(index) {
			var strMarginNow = $('.sEpgShows').css('margin-top').replace('px', '');
			var iMarginNow = parseInt(strMarginNow);
			var height = $('.sEpgShows').height() * -1;
			if (iMarginNow  > height + 300)
				return iMarginNow - 50 + 'px';
			else
				return iMarginNow + 'px';
		});
	});
});

function ImageLoopStart( CSS )
{
	var elements = $(CSS);
	if( elements.length > 1 )
	{
		setInterval(  "ImageLoop('"+CSS+"')", 7000 );
	};
};

function ImageLoop( CSS )
{
	var Now = $(CSS+':visible').fadeOut( 2000 );
	var Next = ( Now.next().is(CSS) && Now.next() ) || $(CSS+':first' );

//	var newBg = $('#bigbackgrounds').find("li:visible").next().children('.hiddenBg').html();
	
/*	if ( newBg == null )
	{
		newBg = $('#bigbackgrounds').find("li:first").children('.hiddenBg').html();
	}

	newBg = newBg.replace('&amp;', '&');

	$('ul#bigbackgrounds li').css('background', newBg);
*/
	Next.fadeIn( 2000 );

};

function showLoad()
{
	if($('#LoadOverlay').length == 0 || $('#LoadingIcon').length == 0)
	{
		$('body').append('<div id="LoadOverlay"></div>');
		$('body').append('<div id="LoadingIcon"><img alt="loading" src="/library/template/icons/loader.gif"/></div>');

		$('#LoadOverlay').show().fadeTo(200, 0.5);
		$('#LoadingIcon').show().fadeTo(200, 1);
	}
}

function hideLoad()
{
	$('body #LoadOverlay').remove();
	$('body #LoadingIcon').remove();
}


/**********************************************/
/**************** Kaupa áksrift ***************/
/**********************************************/

function animateHtml(element,value)
{
	if(element.timeoutId)
	{
		clearTimeout(element.timeoutId);
	}

	var currentValue = parseInt(element.innerHTML);

	
	if(currentValue != value)
	{
		var nextValue = (value > currentValue) ? currentValue+1 : currentValue-1;
		element.innerHTML = nextValue;

		element.timeoutId = setTimeout(function(){animateHtml(element,value)},50);
	}
}

function CartCommandUnAuthenticated(command,packageId)
{	
	var totalPrice = 0;
	var totalDiscountPrice = 0;
	var discountPercent = 0;
	var totalVildPackages = 0;

	var packageById = new Array();
	
	//* Alter state
	for(var i = 0; i < _cartstate.packages.length; i++)
	{
		var package = _cartstate.packages[i];

		packageById[package.id] = package;
		package.subprice = 0;

		//* Apply commands
		if(package.id == packageId)
		{
			if(command == 'RegisterSubscription')
			{
				package.selected = true;
				package.vild = true;
			}
			else if(command == 'CancelSubscription')
			{
				package.selected = false;
			}
			else if(command == 'RemoveSubscriptionOneMonth')
			{
				package.vild = true;
			}
			else if(command == 'UpdateSubscriptionOneMonth')
			{
				package.vild = false;
			}
		}						
	}




	//* Logic

	//* Calculate subprices
	for(var i = 0; i < _cartstate.packages.length; i++)
	{
		var package = _cartstate.packages[i];

		if(package.selected)
		{
			if(package.parentid != '')
			{
				packageById[package.parentid].subprice += package.price;
			}
		}
	}

	for(var i = 0; i < _cartstate.packages.length; i++)
	{
		var package = _cartstate.packages[i];
		if((package.subprice > package.price) || (package.selected && package.subprice > 0))
		{
			package.selected = true;
			for(var j = 0; j < _cartstate.packages.length; j++)
			{									
				var subpackage = _cartstate.packages[j];
				if(subpackage.parentid == package.id)
				{
					subpackage.selected = false;
				}
			}
		}
	}

	//* Calculate total price
	for(var i = 0; i < _cartstate.packages.length; i++)
	{
		var package = _cartstate.packages[i];
		if(package.selected)
		{
			totalPrice += package.price;
			if(package.vild) totalVildPackages ++;
		}
	}

	if(totalVildPackages == 1) discountPercent = 5.0;
	else if(totalVildPackages == 2) discountPercent = 20.0;
	else if(totalVildPackages == 3) discountPercent = 25.0;
	else if(totalVildPackages > 3) discountPercent = 30.0;

	//* Calculate discount price
	for(var i = 0; i < _cartstate.packages.length; i++)
	{
		var package = _cartstate.packages[i];
		if(package.selected)
		{	
			totalDiscountPrice += Math.round(package.price * (1 - (discountPercent / 100)));
		}
	}

	_cartstate.totalPrice = totalPrice;
	_cartstate.totalDiscount = totalPrice - totalDiscountPrice;
	_cartstate.discountPercent = discountPercent;
	_cartstate.totalPriceWithDiscount = totalDiscountPrice;

	AddCartToCookie(_cartstate);
	UpdateCalculator(_cartstate);
}


function channelOnClick(thisElement)
{

	var element = $(thisElement);
	var packageid = thisElement.id;

	if(element.hasClass('selected'))
	{
		CartCommand('CancelSubscription',packageid);
	}
	else
	{
		CartCommand('RegisterSubscription',packageid);
	}

	return false;
}


function AddCartToCookie(state)
{					
	var cookie = "<cart>";
	
	for(var i = 0; i < state.packages.length; i++)
	{
		var package = state.packages[i];
		if(package.selected)
		{
			cookie += "<item><packetid>";
			cookie += package .id + "</packetid><vild>";
			cookie += package.vild ? "1" : "0";
			cookie += "</vild></item>";
		}
	}

	cookie += "</cart>";

	document.cookie = "Cart=" + cookie;
}

function UpdateCalculator(state)
{
	var packages = state.packages;
	
	$('#totalnumber').html(priceTransform(state.totalPrice));
	$('#discountnumber').html(priceTransform(state.totalDiscount));
	$('#totalpricenumber').html(priceTransform(state.totalPriceWithDiscount));
	//$('#percentBig').html(state.discountPercent);
	animateHtml($('#percentBig')[0],state.discountPercent);

	if (state.message == 'CancelSubscriptionNotAllowed'){
		$('#hiddenMessageBox').html('Ekki er unnt að minnka við sig áskrift á þínum síðum. <br/> Vinsamlegast hafðu samband við þjónustufulltrúa í síma 512 5100.');
		$('#hiddenMessageBox').show().fadeTo(200, 1);
	}
	else {
		$('#hiddenMessageBox').hide()
	}

	for(var i = 0; i < packages.length; i++)
	{
		$('#' + packages[i].id).toggleClass('selected',packages[i].selected);
		$('.channel-' + packages[i].name).toggleClass('hidden',!packages[i].selected);
		$('.channel-' + packages[i].name + ' .price').html(priceTransform(Math.round(packages[i].price * (1 - (state.discountPercent / 100)))));
		$('.channel-' + packages[i].name + ' .checkbutton').toggleClass('vild',packages[i].vild);

		$('.extrachannel-' + packages[i].name).toggleClass('hidden',!packages[i].selected);
		$('.extrachannel-Vild-' + packages[i].name).toggleClass('hidden',!packages[i].selected || !packages[i].vild);

	}

	var percentText = "Engin stöð er valin í vild.<br/> 0% afsláttur af grunnverði"; 
	var vildtext="";	

	if(state.discountPercent == 5) { percentText = "Ein áskriftarstöð í Stöð 2 Vild.<br/>5% afsláttur af grunnverði"; vildtext=""; }
	else if(state.discountPercent == 20) { percentText = "Tvær áskriftarstöðvar í Stöð 2 Vild.<br/>20% afsláttur af grunnverði"; vildtext="Silfur"; }
	else if(state.discountPercent == 25) { percentText = "Þrjár áskriftarstöðvar í Stöð 2 Vild.<br/>25% afsláttur af grunnverði"; vildtext="Gull"; }
	else if(state.discountPercent == 30) { percentText = "Fjórar áskriftarstöðvar í Stöð 2 Vild.<br/>30% afsláttur af grunnverði"; vildtext="Platinum"; }
	else if(state.discountPercent > 30) { percentText = "Sérkjör"; vildtext=""; }

	$('#percentText').html(percentText);
	$('#vildText').html(vildtext);

	var percentIcon = "";
	percentIcon = (state.discountPercent == 0) ? "/library/template/subscription/vild_logo_novild.png" : "/library/template/subscription/vild_logo.png";
	$('#percentIcon img').attr("src",percentIcon);
}			

function toggleVild(caller,packageId)
{
	var element = $(caller);
	if(element.hasClass('vild'))
	{
		CartCommand('UpdateSubscriptionOneMonth',packageId);
	}
	else
	{
		CartCommand('RemoveSubscriptionOneMonth',packageId);
	}

	return false;
}

function priceTransform(amount)
{
	return (amount > 1000) ? String(amount).substring(0,(String(amount).length % 3)) + "." + String(amount).substring((String(amount).length % 3),6) : amount;
}

function getCartFromCookie()
{
	return $.cookie('Cart');
}


function showImage(id)
{
	if($('#imgContainer').length == 0)
	{
		$('body').append('<div id="imgContainer"></div>');
	}
	$('#imgContainer').html('<img class="episodeMedium" src="/lisalib/getfile.aspx?itemid=' + id + '&proc=episode-medium" /><a href="/lisalib/getfile.aspx?itemid=' + id + '" target="_blank">Sækja í fullri stærð</a>');
	$('#imgContainer').popup(function(){});

	return false;
}

function showInfoBox(id)
{	
	var containerName = '#epgInfoBox' + id;
	$(containerName).popup(function(){});

	return false;
}

/**********************************************/
/**********************************************/
/**********************************************/

function SetVideoSource(source)
{
	if(player != null)
	{
		$('#videocontainer').popup(function(){ if (player) player.sendEvent('STOP'); });

		setTimeout(function() {
			player.sendEvent('LOAD', source);
		},1000);
	}
	else
	{
		setTimeout(function(){
			SetVideoSource(source);
		},10);
	}
}

function playvideo(id)
{
	if(player == null)
	{
		$('#videocontainer').popup(function(){ if (player) player.sendEvent('STOP'); });
		createPlayer();
	}
	SetVideoSource('/lisalib/getfile.aspx?itemid=' + id + '&filename=video.flv');
}



/* Flash player */

var player = null;
function playerReady(thePlayer) 
{
	player = window.document[thePlayer.id];
}


function createPlayer() {
	var flashvars = {
		file:"",
		autostart:"true",
		controlbar:"over",
		screencolor:"FFFFFF"
	}

	var params = {
		allowfullscreen:"true", 
		allowscriptaccess:"always"
	}

	var attributes = {
		id:"player1",  
		name:"player1"
	}

	swfobject.embedSWF("/library/skrar/player.swf", "videowrapper", "430", "237", "9.0.115", false, flashvars, params, attributes);
}

/*--------------------------------*/
/*flash player fyrir haustkynningu*/
/*--------------------------------*/
function SetLargeVideoSource(source)
{
	if(player != null)
	{
		$('#videocontainer').popup(function(){ if (player) player.sendEvent('STOP'); });

		setTimeout(function() {
			player.sendEvent('LOAD', source);
		},1000);
	}
	else
	{
		setTimeout(function(){
			SetLargeVideoSource(source);
		},10);
	}
}

function playLargeVideo(id)
{	
	if(player == null)
	{
		$('#videocontainer').popup(function(){ if (player) player.sendEvent('STOP'); });
		createLargePlayer();
	}
	SetVideoSource('/lisalib/getfile.aspx?itemid=' + id + '&filename=video.flv');
	 $(".PopupWrapper").attr("style","margin-left:-125px;");
}

function createLargePlayer() {
	var flashvars = {
		file:"",
		autostart:"true",
		controlbar:"over",
		screencolor:"FFFFFF"
	}

	var params = {
		allowfullscreen:"true", 
		allowscriptaccess:"always"
	}

	var attributes = {
		id:"player1",  
		name:"player1"
	}
	$(".PopupWrapper").attr("style","width:900px");
	swfobject.embedSWF("/library/skrar/player.swf", "videowrapper", "860", "474", "9.0.115", false, flashvars, params, attributes);
}


/* Dropdown */
var dropDownMaxHeight = 400;
$(function(){
    $(".dropdown > li").hover(function() {
             var $container = $(this),
             $list = $container.find("ul"),
             $anchor = $container.find("a"),
             height = $list.height() * 1.1,       // make sure there is enough room at the bottom
             multiplier = height / dropDownMaxHeight;     // needs to move faster if list is taller
        $container.data("origHeight", $container.height());
        $anchor.addClass("hover");
        $list
            .show()
            .css({
                paddingTop: $container.data("origHeight")
            });
        if (multiplier > 1) {
            $container
                .css({
                    height: dropDownMaxHeight,
                    overflow: "hidden"
                })
                .mousemove(function(e) {
                    var offset = $container.offset();
                    var relativeY = ((e.pageY - offset.top) * multiplier) - ($container.data("origHeight") * multiplier);
                    if (relativeY > $container.data("origHeight")) {
                        $list.css("top", -relativeY + $container.data("origHeight"));
                    };
                });
        }
    }, function() {
        var $el = $(this);
       $el
            .height($(this).data("origHeight"))
            .find("ul")
            .css({ top: 0 })
            .hide()
            .end()
            .find("a")
            .removeClass("hover");
    });
});
