var really_fade_tooltip = false;
var really_hide_tooltip = false;

/**
 * Executed when document is finished loading elements into DOM
 */
$(document).ready(function()
{
	
	if ($.browser.msie && $.browser.version.substr(0,1)<7){
		$("img[src$='.png']").each(function(){$(this).addClass("png");});
		
		$('div#content .shop-view').css('height', 'auto');
		$('div#content .shop-view').width(690);
	}
	
	/**
	 * Display confirmation dialog whenever link
	 * with className "confirm" is slicked
	 */
	$(".confirm").click(function(){
		return confirm("Vai tiešām vēlaties veikt šo darbību?");
	});
	
	// strech background container to fit window height
	if ($("#container").height() > $("body").height())
	{
		var height = parseInt($("#container").height());
	}
	else
	{
		var height = parseInt($("body").height());
	}

	$("#background").css("height", height+"px");
	
	/*Initialize a custom scrolbar*/
	$(function()
	{
		$('.scroll-pane').jScrollPane({
			animateTo:true,
			dragMinHeight:50,
			dragMaxHeight:50,
			reinitialiseOnImageLoad:true,
			scrollbarWidth:11
		});
	});	
	
	$(function() {		
		
		$('a.lightbox').lightBox({
			txtImage: '',
			txtOf: '/'	
		}); // Select all links with lightbox class
	});
	
	$('#map-areas area').mouseover(function(event){
		really_hide_tooltip = false;
		$('#shop-tooltip').show();
		shop_id = $(this).attr('id').split('-')[1];
		
		img_src = 'url('+webroot+'img/shops/medium_'+shop_id+'.jpg)';
		
		if (typeof(shops[shop_id]) == 'undefined'){
			if ($('#shop-tooltip div').css('background-image') != img_src){
				$('#shop-tooltip div').css('background-image', img_src);
				$('#shop-tooltip span').hide();
			}
		}else{
			$('#shop-tooltip div').css('background-image', 'none');
			$('#shop-tooltip span').html(shops[shop_id]).show();
		}
	});
	
	$('#map-areas area, #shop-tooltip').mousemove(function(event){
		$('#shop-tooltip').css('top', event.pageY - 80);
		$('#shop-tooltip').css('left', event.pageX - 58);
	});
	
	$('#map-areas area, #shop-map-img').mouseleave(function(){
		really_hide_tooltip = true;
		setTimeout("hideTooltip();", 100);
	});
	
	$('#map-areas area, #shop-map-img').mouseover(function(){
		really_fade_tooltip = false;
		
		$('#shop-tooltip-clone').hide();
		//$('#shop-tooltip-clone').animate({opacity: 0}, 1000, null, function(){ $('#shop-tooltip-clone').hide(); });
	});
	
	$('#map-areas area, #shop-map-img').mouseleave(function(){
		really_fade_tooltip = true;
		setTimeout("fadeTooltip();", 100);
	});
	
	//SETTING UP POP UP WINDOW FUNCTIONALITY
	 
	//0 means disabled; 1 means enabled;
	var popupStatus = 0;  
	
	//loading popup with jQuery magic!
	function loadPopup(id){
		//loads popup only if it is disabled
		if(popupStatus==0){
			
			//Disable a flash background of Domina website
			$("#background").hide();
			
			$("#backgroundPopup").css({
				"opacity": "0.7"
			});
			$("#backgroundPopup").fadeIn("slow");
			$("#puw_"+id).fadeIn("slow");
			popupStatus = 1;			
		}
	}
	
	//disabling popup with jQuery magic!
	function disablePopup(id){
		//disables popup only if it is enabled
		if(popupStatus==1){
			$("#backgroundPopup").fadeOut("slow");
			$(".popupBox").fadeOut("slow");
			popupStatus = 0;
		}
		
		//Enable a flash background of Domina website
		$("#background").show();
	}
	
	//centering popup
	function centerPopup(id){		
		//request data for centering
		var windowWidth = document.documentElement.clientWidth;
		
		var windowHeight = document.documentElement.clientHeight;		
		
		var popupHeight = $("#puw_"+id).height();
		var popupWidth = $("#puw_"+id).width();
		//centering
		$("#puw_"+id).css({
			/*"position": "absolute",*/
			"top": windowHeight/2-popupHeight/2,
			"left": windowWidth/2-popupWidth/2
		});		
		
		//only need force for IE6
		$("#backgroundPopup").css({
			"height": windowHeight			
		});
	}
	
	//LOADING POPUP
	//Click the button event!
	$("a.extraBanner").click(function(){
		
		// Get popupBox Id	
		var id = $(this).attr("id");
				
		//centering with css
		centerPopup(id);
		//load popup
		loadPopup(id);
	});
	
	//CLOSING POPUP
	//Click the x event!
	$(".popupBoxClose").click(function(){
		var close_id = $(this).attr("id");
		var id = close_id.substring(6);		
		disablePopup(id);
	});
	//Click out event!
	$("#backgroundPopup").click(function(){
		disablePopup();
	});
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();
		}
	});

	
	
	//if($.cookie('domina_bg_movie') && $.cookie('domina_bg_movie')=="stop")
	if($.cookie('domina_bg_movie')=="start")
	{
		startStop("start");
	} else
	{
		startStop("stop");
	}
	
	$('#slides .item').css('opacity', '0');
	$('.floating-text').css('opacity', '0');

	// Categorize items in Shopping guide
	$('a.item_category')
	.click(function()
	{				
		var cat_id = $(this).attr("id");
		var id = cat_id.substring(4);
		
		$('.item_category').removeClass("active");
		$('#' + cat_id).addClass("active");
		
		if( id == "all")
		{
			$('.product').slideDown("fast");
		}
		else
		{
			$('.product').hide();
			$('.type_' + id).slideDown("slow");
		}		
		
		return false;
	})
	
	SetupAJAXCommentSubmit();
	SetupAJAXPagination('.pagination', '#comments');
	
	// Set scrollable on second page to support looping		
		$("div.scrollable").one("focus", function(){
      var slider = $("div.scrollable").scrollable(); 
      slider.setPage(1);         
    });
    
   /* $("div.scrollable").click(function () {
  		//var slider = $("div.scrollable").scrollable(); 
    	//slider.setPage(1);     	
	});
	
	$("div.scrollable").ready(function () {
    	var slider = $("div.scrollable").scrollable(); 
    	slider.setPage(1);   
	});*/
	
	//$("div.scrollable").scrollable().click(0).seekTo(1, 3000, function() { 
    	
    	//this.setPage(1);         
	//});
	
	$('#content.brands #categories .column .item a').click(function(){
		if ($(this).parent().attr('class') != 'children'){
			$('#categories .column .item .children').hide();
			$('.scroll-pane')[0].scrollTo($('h2[name='+$(this).attr('href').replace('#', '')+']').position().top);
		}else{
			$('.scroll-pane')[0].scrollTo($('h3[name='+$(this).attr('href').replace('#', '')+']').position().top);
		}
		$(this).parent().children('.children').show();
		
		$('#categories .column .item a').removeClass('active');
		$(this).addClass('active');
	});
//	
//	$('#category-brands .item .item').mouseover(function(){
//		$(this).children('a').children('.text').css('color', '#FFFFFF');
//	});
//	
//	$('#category-brands .item .item').mouseleave(function(){
//		$(this).children('a').children('.text').css('color', '#777777');
//	});

});

/**
 * Print email link (protection from spambots)
 * If javascript is disabled, nothing is visible
 *
 * @param string p1 Part 1 - this is username
 * @param string p2 Part 2 - this is domain and TLD
 */
function writemail(id, p1, p2)
{
	//document.write("<a href='mailto:"+p1+"@"+p2+"'>"+p1+"@"+p2+"</a>");
	$('#' + id).html("<a href='mailto:"+p1+"@"+p2+"'>"+p1+"@"+p2+"</a>"); 	
}

function hideTooltip(){
	if (really_hide_tooltip){
		$('#shop-tooltip').hide();
	}
}

function showTooltip(id, top, left){
	$('#shop-tooltip-clone').show();
}

function fadeTooltip(){
	if (really_fade_tooltip){
		$('#shop-tooltip-clone').show();
		//$('#shop-tooltip-clone').css('opacity', 1);
		//$('#shop-tooltip-clone').animate({opacity: 1}, 1000);
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

/* BG controls */
function getFlashMovie(movieName) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}

function startStop(action) {
	createCookie("domina_bg_movie",action,356);
	var other = new Array();
	other["stop"] = "start";
	other["start"] = "stop";
	if(action == "stop")
	{
		$("#background").hide();
		$("#bgControls_off").hide();
		$("#bgControls_on").show();
	} else
	{
		$("#background").show();
		$("#bgControls_off").show();
		$("#bgControls_on").hide();
	}	
	//getFlashMovie("domina").startStopVideo(action);
}

function SetupAJAXPagination(filter, divContent) {
	$(filter).find('a[href*=/sort:],a[href*=/page:]').click(function() 
	{
		$.ajax({
		type: "GET",
		url: this.href,
		cache: false,
		success: function(msg) 
		{				
			$(filter).html($(msg).find(filter).html());	
					
			//Need to load newest content to comments					
			$(divContent).html($(msg).find(divContent).html());		
			SetupAJAXPagination(filter, divContent);				
		}
		});
		return false;
	});
}

function SetupAJAXCommentSubmit() {
	// Save a comment in Article
	$('#commentSubmit')
	.click(function()
	{				
		$(this).parents("form:first").ajaxSubmit({
			success: function(responseText, responseCode) 
			{
				$('#form #messages').hide().html(responseText).fadeIn();
				setTimeout(function()
				{
					$('#form #messages').fadeOut();
				}, 5000);
				
				var owner_id = $('#CommentsOwnerId').attr('value');	
				var owner_type = $('#CommentsOwnerType').attr('value');	
				
				// Clear input fields
				$('#form .text input').attr('value', null);	
				$('#form .textarea textarea').attr('value', null);		
				
				switch(owner_type)
				{				  
					case "1":
					   owner_type = "faq";
					break;
					default:
					  owner_type = "article";
					break;
				}								
				
				$.ajax({
					type: "GET",
					cache: false,
					url: webroot + language + "/d-mag/" + owner_type  + "/" + owner_id + "/page:1",
					success: function(msg) {			
						
					// Update pagination links and comments content
					$(".pagination").html($(msg).find(".pagination").html());									
					$("#comments").html($(msg).find("#comments").html());	
							
					}
				});
				return false;
				
				
			}
		});

		return false;
	})
}

var rotate_banners = true;
var current_banner_key = 0;

function showBanner(banner_id, auto){
	if (auto){	
		rotate_banners = false;
	}
	
	if ($('#top #tabs a.active').length != 0){
		old_id = parseInt($('#top #tabs a.active').attr('class').split(' ')[0]);
		
		if (old_id != banner_id){			
			if ($('#slides .item.'+old_id).hasClass('image')){
				$('#slides .item.'+old_id+', #slides .item.'+old_id+' .floating-text').animate({
					'opacity' : 0
				}, 1000, null, function(){ $('#slides .item.'+old_id).hide() });
			}else{
				$('#slides .item.'+old_id+', #slides .item.'+old_id+' .floating-text').hide();
			}
		}
	}
	
	$('#top #tabs a').removeClass('active');
	$('#top #tabs a.'+banner_id).addClass('active');
	
	if ($('#slides .item.'+banner_id).hasClass('image')){
		$('#slides .item.'+banner_id+', #slides .item.'+banner_id+' .floating-text').show().animate({
			'opacity' : 1
		}, 1000);
	}else{
		$('#slides .item.'+banner_id+', #slides .item.'+banner_id+' .floating-text').css('opacity', 1).show();
	}
}

function rotateBanners(){
	if (rotate_banners){
		showBanner(banner_ids[current_banner_key].id, false);

		last_banner_key = current_banner_key;
		current_banner_key++;
		if (current_banner_key == banner_ids.length){
			current_banner_key = 0;
		}
		
		setTimeout('rotateBanners();', banner_ids[last_banner_key].timeout);
	}
}

function addBazaraFields(){
	for (i = 0; i < 3; i++){
		$('#bazara-fields').append('<tr>'+$('#field-dummy').html().replace(/number/gi, $('#bazara-fields tr').length - 1)+'</tr>');
	}
	return false;
}