/*
	@Authors  : 
	Cvetozar Ninov, Boris Delev 
*/
var acc = null;

var modules = new Array('books','handicrafts','music','dvd','cd','apparels');

// For popup
var cache_popups = new Array();
var popup_open = false;
var popup_timer = 0;

function in_array(array,obj)
{
	return (array[obj]) ? true : false;
}

jQuery().ready(function(){
	$('.search_box li').click(function(){
		$('li',this.parentNode).removeClass('active');
		$(this).addClass('active');

        if(modules[$('.search_box li').index(this)] == 'books'){
            $('<option value="author_name">Author</option>').appendTo($('#search_type'));
            $('<option value="isbn10">ISBN-10</option>').appendTo($('#search_type'));
            $('<option value="isbn13">ISBN-13</option>').appendTo($('#search_type'));
            $('<option value="publisher">Publisher</option>').appendTo($('#search_type'));
        }else{
            $('#search_type option[value="author_name"]').remove();
            $('#search_type option[value="isbn10"]').remove();
            $('#search_type option[value="isbn13"]').remove();
            $('#search_type option[value="publisher"]').remove();
        }
	});

	jQuery('#menu div').accordion({
		autoheight: false,
		alwaysOpen: false,
		active: '.selected',
		selectedClass: 'active',
		header: "span"
	});

	jQuery('div#faqs').accordion({
		autoheight: false,
		alwaysOpen: false,
		active: '.selected',
		selectedClass: 'active',
		header: "p.button"
	});
	
	$('A[rel="gift"]').click( function() { 
        window.open( $(this).attr('href'), "Bagchee:: GiftCard","height=342,width=486,status=yes,toolbar=no");
        return false;
    });

	//Appearing and disappearing blocks
	$("div.split>h2").each( function( intIndex ){
		$(this).bind ("click", function(){
			if (!$(this).hasClass("inactive")) {
				var current_number = intIndex+1;
				$('div.split').removeClass('current');
				$(this).parents('div.split').addClass('current');
				var titles = $("div.current h2");
	
				titles.removeClass('left_active');
				titles.removeClass('middle_active');
				titles.removeClass('right_active');
	
				if ($(this).hasClass("left")) {
					$(this).addClass('left_active');
				}
				else if ($(this).hasClass("right")) {
					$(this).addClass('right_active');
				}
				else {
					$(this).addClass('middle_active');
				}
	
				$('div.current div.block').hide();
				$('div.current div.block_'+current_number).show();
			}
		});
	});



	//Personal and company account form
	jQuery("input[name='account']").click(function (){
		var current = this.id;
		$('fieldset[class!=fixed]').hide();
		$('fieldset.' + current).show();

	});


	//Add new user
	jQuery("div#add_new_user_btn").click(function (){
		$('form#add_new_user').show();
		$('div.manage_participants').hide();
	});

	jQuery("form#add_new_user a.back").click(function (){
		$('form#add_new_user').hide();
		$('div.manage_participants').show();
	});

	jQuery("div.manage_participants a.edit").click(function (){
		$('form#edit_user').show();
		$('div.manage_participants').hide();
	});

	// Open banner on top
	$('.header .shipping_banner .right_corner a').click(function() {
		$('.shipping_banner_container').fadeIn('fast');

		$('.header .shipping_banner_container a.close').click(function() {
			$('.header .shipping_banner_container').fadeOut('fast');
		});
	});


	// Blink flash messages
	$('#flash_messages').animate({"opacity": "0.5"}, "fast").animate({"opacity": "1"}, "fast").animate({"opacity": "0.5"}, "fast").animate({"opacity": "1"}, "fast");

	$('#flash_messages a.close').click( function() {
		$('#flash_messages').hide('slow');
	});

	//##### Clear after click
	$('.clear_on_click').focus(function() {
		var value = $(this).attr('title');

		if (value != '')
		{
			if ($(this).val() == value)
			{
				$(this).val('');
			}

			$(this).blur(function() {
				if ($(this).val() == '')
				{
					$(this).val($(this).attr('title'));
				}
			})
		}
		else
		{
			$(this).val('');
		}
	});

	//##### Custom selects
	$('.custom_select').click(function(){
		// Element properties
		var element = $(this);

		var element_name = $(this).attr("name");

		var element_position = $(this).position();

		var element_dimensions = $(this).innerWidth();

		// Select box
		var element_variables = $('#' + element_name);
		element.val($('option:selected', element_variables).text());

		// When...
		element.each(function() {
			if (element_variables)
			{
				if (element_variables.css('display') == 'none')
				{
					var margin = parseInt($(this).css('margin-bottom'));

					// Set dimensions
					element_variables.css('left', element_position.left);
					element_variables.css('top', element_position.top - margin);
					element_variables.css('width', element_dimensions);

					// Set size
					var element_items = $('option', element_variables);
					var how_many_variables = element_items.length;
					if (how_many_variables > 5) how_many_variables = 5;
					element_variables.attr('size', how_many_variables);

					// Set actions
					element_variables.blur(function() {
						element_variables.hide();
					});

					element_variables.click(function() {
						element.val($('option:selected', element_variables).text());
						element_variables.hide();
					});

					// Show it and set focus
					element_variables.fadeIn();
					element_variables.focus();
				}
				else
				{
					element_variables.hide();
				}
			}
		});
	}).each(function(){
		var element_name = $(this).attr("name");
		var element_variables = $('#' + element_name);

		$(this).val($('option:selected', element_variables).text());
	});

	$('.shopping_bag span.bag_number').bind("click", function(){
	   	$.get(bag_popup,{},function(data){
	   		$('.shopbag_popup').html(data);
	   		$('.popup_content li:last').addClass('last_item');
	   		$('.shopbag_popup').show('slow');
	   	})
	});


	acc = jQuery('#checkout div.accordeon').accordion({
		autoheight: false,
		alwaysOpen: false,
		active: '.selected',
		selectedClass: 'active',
		header: "h3",
		animated: 'easeslide'
	});


	$('.breadcrumb .tools .tell_friend a').click(function() {
		$('.tell_a_friend').fadeToggle();
	});

	$('a.security_card').click(function() {
		$('.security_card_info').fadeToggle();
	});

	

	var index = $('.navigation li').index($('.navigation li.active_li'));
	index = (index >= 0) ? index : 0;
	$('div.search_box ul li:eq('+index+')').click();

    $('#search_input').keydown(function(ev){
        if(ev.keyCode == 13){
            submit_search();
        }
    });
    $('.search_box button.hidden').click(function(){submit_search();});
});

jQuery.fn.fadeToggle = function(speed, easing, callback) {
   return this.animate({opacity: 'toggle'}, speed, easing, callback);
};

// submit search
function submit_search(){
    var selected_search = $('div.search_box ul li.active').click();
    var index = $('div.search_box ul li').index(selected_search);
    window.location = _site_root+'en/search/results/?' + $('#search_type').val() + '='+$('#search_input').val() + '&module=' + modules[index];
}

// Load Flash function
function loadFlash( fname, w, h, params )
{
	var add_params = '';

	if ( params )
	{
		for( param in params ) {
			add_params += '<param name="'+param+'" value="'+params[param]+'" />';
		}
	}

	var Flash = ' \
		<object type="application/x-shockwave-flash" data="' + fname + '" width="' + w + '" height="' + h + '"> \
		<param name="quality" value="high" /> \
		<param name="scale" value="noscale" /> \
		<param name="wmode" value="transparent" /> \
		' + add_params + ' \
		<param name="movie" value="' + fname + '" /> \
		</object> \
	';

	document.write( Flash );
}


// Clear recently items
function clear_recently_items()
{
	$.get( _site_root + "application/clear_recently_items");
	$('#sidebar .recently_viewed').fadeOut(800);
}

// Go to newsletter
function submit_to_newsletter()
{
	var value = $('#sidebar .newsletter .input input').val();
	window.location.href =  _site_root + 'newsletter?mail=' + value;
}

function add_flash_message(message)
{
	 $('html,body').animate({scrollTop: 0}, 1000, function(){
		 $('#flash_messages').remove();
		 var flash_message = $('<div style="display: none;" id="flash_messages"><a class="close" href="javascript:;">Hide</a><ul><li>'+message+'</li></ul></div>');

		 $('#main_content').before(flash_message);
		 $(flash_message).show('slow');

		$('#flash_messages a').click( function() {
			$(this).parent().hide('slow',function(){});
		});
	 });
}

function add_to_wishlist(prd, tp)
{
	$.get(_site_root + "my/wishlist_add", { product: prd, type: tp },
		function(data){
			add_flash_message(data);
		}
	);
}

// Show details for product
// I use four function - one for timeout, one for getting the information, for show the box and one for clear all elements
function show_details_for(el, prd, tp)
{
	if (popup_timer)
	{
		clearTimeout(popup_timer);
	}

	popup_timer = setTimeout(function(){
		show_details_checker(el, prd, tp);
	}, 300);
}
function show_details_checker(el, prd, tp)
{
	var element = $(el);
	var details = false;

	if (element && prd && tp)
	{
		if (in_array(cache_popups,tp))
		{
			if (in_array(cache_popups[tp],prd))
			{
				details = cache_popups[tp][prd];
			}
		}
		else
		{
			cache_popups[tp] = new Array();
		}

		// Check if is open
		if (popup_open != false)
		{
			if (popup_open != tp + '_' + prd)
			{
				popup_open = false;
			}
		}

		if (popup_open == false)
		{
			// Add effect
			element.animate({
				opacity: 0.5
			}, 300, false, function() { if (details == false) $(this).addClass('loading'); } )

			if (details == false)
			{
				$.get(_site_root + "application/show_popup_information", { product: prd, type: tp },
					function(data){
						if (data != '')
						{
							cache_popups[tp][prd] = data;
							show_details_put_element(element, data);
						}
					}
				);
			}
			else
			{
				show_details_put_element(element, details);
			}

			popup_open = tp + '_' + prd;
		}
		else
		{
			show_details_hide_all();
			popup_open = false;
		}
	}
}
function show_details_put_element(element, details)
{
	if (element && details)
	{
		var element_position = element.position();
		var margin = parseInt(element.css('margin-bottom'));

		// Hide all
		show_details_hide_all();

		// Add new
		//var parent = element.parent().parent();
		var parent = $('#content .box_left_corner');
		parent.append(details);

		// Calculate dimensions
		var container = $('div.container').position();
		var width = $('div.container').css('width');

		// Change positions
		if (element_position.left <= 480)
		{
			$('.info_popup').removeClass('reversed_popup');
			$('.info_popup').css('left', element_position.left - 15);
			$('.info_popup').css('top', element_position.top - margin);
		}
		else
		{
			$('.info_popup').addClass('reversed_popup');
			$('.info_popup').css('left', element_position.left - 375);
			$('.info_popup').css('top', element_position.top - margin);
		}

		// Show
		$('.info_popup').fadeIn();
	}

	// Remove effect
	element.removeClass('loading');
	element.animate({
		opacity: 1
	}, 300, false, function() {element.removeClass('loading')});
}
function show_details_hide_all()
{
	// Delete all
	$('.info_popup').remove();
}

function add_to_bag(prd, tp, amount, show_flash_messages)
{

	if(typeof(amount)=='undefined') {
		amount = 1;
	}
	if(typeof(show_flash_messages)=='undefined') {
		show_flash_messages = true;
	}
	$.get(_site_root + "shopping_bag/add", { product: prd, type: tp,quantity: amount },
		function(transport){
			if (show_flash_messages) add_flash_message(transport.message);
			$('.bag_number').html(transport.items_count);
			$('.bag_number').show('slow');
	   		$('.shopbag_popup').hide('slow');
		}
	,'json');
}

function send_to_friend()
{
	var fields = $('.tell_a_friend');
	if (fields)
	{
		//your_name your_mail recip_mail
		var name = $(('#your_name'), fields).val();
		var mail = $(('#your_mail'), fields).val();
		var recipient = $(('#recip_mail'), fields).val();
		if (name && mail && recipient)
		{
			$.post(_site_root + "my/send_to_friend", { names: name, from_mail: mail, to_mail: recipient },
				function(data){
					if (data != '') add_flash_message(data);
				}
			);

			fields.fadeToggle();
		}

		$(('#your_name'), fields).val('');
		$(('#your_mail'), fields).val('');
		$(('#recip_mail'), fields).val('');
	}
}
