function ShowLoginForm()
{
    $('#loginform').toggle();
    $('input[name=login]').focus();

    overlay();

    $(document).bind('keydown', 'Esc', function(){CloseMessage('loginform')} );
	$('#bg').unbind().click(function() {CloseMessage('loginform')});
	$('a[rel=close]').unbind().click(function() {CloseMessage('loginform')});
}

function ShowDeleteProfileForm()
{
    $('#delete_profile').toggle();
    $('input[name=password]').focus();

    overlay();

    $(document).bind('keydown', 'Esc', function(){CloseMessage('delete_profile')} );
	$('#bg').unbind().click(function() {CloseMessage('delete_profile')});
	$('a[rel=close]').unbind().click(function() {CloseMessage('delete_profile')});
}

function ShowErrorForm()
{
    $('#errorform').toggle();
    $('textarea[name=errortext]').focus();
	
    overlay();

    $(document).bind('keydown', 'Esc', function(){CloseMessage('errorform')} );
	$('#bg').unbind().click(function() {CloseMessage('errorform')});
	$('a[rel=close]').unbind().click(function() {CloseMessage('errorform')});
}

function block(obj)
{
	for(i=1; i<=10; i++)
	{
		if (obj == 'r' + i)
		{
			document.getElementById(obj).style.display = 'block';
			if(document.getElementById(obj + 'h') != null)
				document.getElementById(obj + 'h').style.backgroundImage = 'url('+media_location+'/img/pointer_4b.gif)';
		}
		else
		{
			if(document.getElementById('r' + i) != null)
				document.getElementById('r' + i).style.display = 'none';
				if(document.getElementById('r' + i + 'h') != null)
					document.getElementById('r' + i + 'h').style.backgroundImage = 'url('+media_location+'/img/pointer_4r.gif)';
		}
	}
}


function GetGenres(obj, callback)
{
    $('li[subattr=ajax]').remove();
    $(obj).toggleClass('sel');

    var genresId = new Array();
    $('a[attr=genreP]').each(function(i)
    {
        if($(this).attr("class") == 'sel')
        {
            genresId.push($(this).attr('genre'));
        }
    }
    );

    if(genresId.length == 0)
    {
        $('#insert_in').hide();
        return;
    }
    else
    {
        if($('#insert_in').css('display') == 'none')
        {
            $('#insert_in').show();
        }
        $('#genres_loader').show();
        $('#genres').val();            
    }
        
    $.post(
        http_location + '/index/getgenres',
        {parents : genresId.join(",")},
        function(data) 
        {
            var html = '<li class="clear"><!-- ~ --></li>';
            var length = data.length;
            for(var i = 0; i < length; i++)
            {
                html+= '<li><a style="cursor:pointer" onclick="SelectGenre(this)" attr="genre" subattr="ajax" genre="'+data[i]['Id']+'">'+data[i]['Title']+'</a>'+(i < length-1 ? ',' : '')+'</li>';
            }
			html+= '<li class="clear"><!-- ~ --></li>';
            $('#genres_loader').hide();
            $('#insert_in').html(html);
            
            if(callback) callback(); 
        }
        ,'json'       
    );
}

function SelectGenresFromFieldAndRewrite()
{
    genres = $('#genres').val().split(',');
    for(var i = 0; i < genres.length; i++)
    {
        $('a[genre='+genres[i]+']').addClass("sel");                
    }

    SelectGenre(null);
}

function SelectGenresFromField()
{
    var genres = $('#genres').val().split(',');
    for(var i = 0; i < genres.length; i++)
    {
        $('a[genre='+genres[i]+']').addClass('sel');
    }    
}

function SelectGenre(obj)
{
    $(obj).toggleClass("sel");   

    var genresId = new Array();
    $('a[attr=genre]').each(function(i)
    {
        if($(this).attr("class") == 'sel')
        {
            genresId.push($(this).attr("genre"));
        }
    }
    );

    $('#genres').val(genresId.join(","));     
}

     
function PopupMessage(title, text)     
{
    overlay();
        
    $(document).bind('keydown', 'Esc', function(){CloseMessage('error_message')} );
	$('#bg').unbind().click(function() {CloseMessage('error_message')});
    $('a[rel=close]').unbind().click(function() {CloseMessage('error_message')});
	
    $("#error_message h2").html(title);
    $("#error_message label").html(text);
    
    $("#error_message").show();   
}     
     
function CloseMessage(id ,destroy)
{
    if(destroy)
    {
        $("*[type=error]").remove();
    }
    else
    {
        if(jQuery.support.cssFloat == true)
            $("#bg").fadeOut('fast');
        else
            $("#bg").hide();       

        $('#'+id).hide();
    }
    $(document).unbind('keydown', 'Esc', null);
}


function OpenDeleteMessage(url)
{
    overlay();
        
    $(document).bind('keydown', 'Esc', function(){CloseMessage('delete')} );
	$('#bg').unbind().click(function() {CloseMessage('delete')});
	$('a[rel=close]').unbind().click(function() {CloseMessage('delete')});

    $('#delete').show();    
    
    $('#delete #btn').click(function () 
    { 
        window.location = http_location + url;
    });    
}

function OpenRestorePasswordForm()
{
    overlay();
	
	$(document).unbind('keydown', 'Esc', null);
    $(document).bind('keydown', 'Esc', function(){CloseMessage('restore')} );
	$('#bg').unbind().click(function() {CloseMessage('restore')});
	$('a[rel=close]').unbind().click(function() {CloseMessage('restore')});

	$('#loginform').hide();
    $('#restore').show();
    $('#restore input[name=email]').focus();                         
}

function OpenSubscriptionForm()
{                                             
    overlay();

    $(document).bind('keydown', 'Esc', function(){CloseMessage('subscribe')} );
	$('#bg').unbind().click(function() {CloseMessage('subscribe')});
	$('a[rel=close]').unbind().click(function() {CloseMessage('subscribe')});

    $('#subscribe').show();
    $('#subscribe input[name=email]').focus();                         
}


function AutocompleteAuthors(id)
{
    $('#'+id).autocomplete(http_location + "/index/authors", {
        multiple: true,
        minChars: 2,
        scroll: true,
        scrollHeight: 300        
    });
}

function AutocompletePublishings(id)
{
    $('#'+id).autocomplete(http_location + "/index/publishings", {
        minChars: 2,
        scroll: true,
        scrollHeight: 300
    });
}

function AutocompleteBooks(id)
{
    $('#'+id).autocomplete(http_location + "/index/books", {
        minChars: 3,
        //mustMatch: true,
        scroll: true,     
        scrollHeight: 300,
        formatItem: function(value, i, n, data) {
            return '<img src="'+value[5]+'" width="50" style="float:left" />' + value[0] + "<br><span style='font-size: 80%;'>" + value[4] + '. ' + value[2] + ", " + value[1] + "</span>";
        },
        formatResult: function(row) {
            return row[0];
        }                  
    }).result(function(event, data, formatted) {
        $('#book_id').val(data[3]);
    });
}

function AttachGoogleInput()
{
	$('input[name=BooksTitle]').keyup(function() {$('a[class=google]').attr('href', 'http://www.google.com/search?q=' + $(this).val())});
}

function AttachUploadBookImageEvent()
{
    new AjaxUpload('#upload_button', {
      action: http_location + "/index/uploadbookimage",
      data: {},
      name: 'image',
      autoSubmit: true,
      responseType: 'json',
      onSubmit: function(file, extension) {
            if (extension && /^(jpg|png|jpeg|gif)$/.test(extension))
            {
                this.disable();
                $('#book_img').attr({'src':media_location+'/img/ajax-loader2.gif', 'width': 66, 'height': 66}); 
            }
            else
            {
                PopupMessage(I18n[0], I18n[1]);
                return false;
            }
      },
      onComplete: function(file, response) {

          if(response[0] == 'error')
          {
              PopupMessage(I18n[0], response[1])
              $('#book_img').attr({'src':media_location+'/img/users/nophoto.jpg','width': 96, 'height': 153});          
          }
          else
          {
              $('#book_img').attr({'src':response[0], 'width':response[2], 'height':response[3]});          
              $('#image_id').val(response[1]);
          }          
          
          this.enable();                       
      }
    });
}

function AttachUploadUserImageEvent(type)
{                                  
    new AjaxUpload('#upload_button', {
      action: http_location + "/index/uploaduserphoto",
      data: {                                 
        user_type : type
      },
      name: 'image',
      autoSubmit: true,
      responseType: 'json',
      onSubmit: function(file, extension) {
            if (extension && /^(jpg|png|jpeg|gif)$/.test(extension))
            {
                this.disable();
                $('#book_img').attr({'src':media_location+'/img/ajax-loader2.gif', 'width': 66, 'height': 66}); 
            }
            else
            {
                PopupMessage(I18n[0], I18n[1]);
                return false;
            }
      },
      onComplete: function(file, response) {         
          if(response[0] == 'error')
          {
              PopupMessage(I18n[0], response[1]);
              $('#book_img').attr({'src':media_location+'/img/users/nophoto.jpg', 'width':201, 'height':194});          
          }
          else
          {
              $('#book_img').attr({'src':response[0], 'width':response[2], 'height':response[3]});          
              $('#image_id').val(response[1]);
          }
          
          this.enable();                       
      }
    });
}


function LoadOrderDetail(id, sort, order, obj)
{
	if($('#basket_'+id).css('display') == 'none' || obj != undefined)
	{
		$('#loader_'+id).show();
		
		$.post(
			http_location + '/orders/loadOrder',
			{pid : id, psort : sort, porder : order},
			function(data)
			{
				$('#loader_'+id).hide();
				$('#basket_'+id).html(data).show();
				
				if(obj != undefined)
				{
					$('a[type=*]').removeClass();
					$('a[type='+sort+']').addClass(order != 'desc' ? 'des' : 'asc');
				}
			}
		);
	}
	else
	{
		if(obj == undefined)
			$('#basket_'+id).html('').hide();
	}
}

function changeStatus(id, status, confirmed)
{
	if(status)
	{
		var newStatus = $('#new_'+id).val();
		
		if(newStatus >= 3 && confirmed == undefined)
		{
			$('#confirm_message').show();
			$('#confirm_message h2').html(I18n[2]);
			$('#confirm_message label').html(I18n[3]);

			$('#btn_ok').bind('click', function() {changeStatus(id, status, newStatus)} );
			$('#btn_cancel').bind('click', function() {changeStatus(id, status, 0)} );
			
			return;
		}

		$('#confirm_message').hide();
		$('#btn_ok').bind('click', function() {});
		$('#btn_cancel').bind('click', function() {});

		if(confirmed == undefined || confirmed > 0)
		{
			$.post(
				http_location + '/orders/changeStatus',
				{pid: id, status : newStatus},
				function(data)
				{
					$('#status_'+id).html(data);
					if(newStatus == 3)
						$('#pic_'+id).remove();
				}
			);
		}
		else
		{
			$('#new_'+id).val(2);
			
			changeStatus(id, status);
		}
	}
	else
	{
		$.post(
			http_location + '/orders/getStatus',
			{pid: id},
			function(data)
			{
				$('#status_'+id).html(data);
			}
		);
	}
}

function FindBook()
{
    if($('#book_search').val() != '')
    {
        SendBookInfoQuery('title')    
    }
    else if($('#isbn_search').val() != '')
    {
        SendBookInfoQuery('isbn');
    }
}

function SendBookInfoQuery(type)
{
    if(!type)
        return false
    if(type == 'isbn')
    {
        var value = $('#isbn_search').val();
        if(value == '')
            return false;
    }   
    else if(type == 'title') 
    {
        var value = $('#book_search').val();
        if(value == '')
            return false;        
    }
    else
        return false
    
    $('#form input, textarea, select').attr('disabled', true);
    $('#book_img').attr({'src':media_location+'/img/ajax-loader2.gif', 'width': 66, 'height': 66}); 
    $('a[attr=genreP]').removeClass("sel");
    GetGenres(null, null);
    
    $.post(
        http_location + '/index/sendbookinfoquery',
        {query : value, querytype : type},
        function(data) 
        {
            $('#form input, textarea, select').removeAttr('disabled');
            $('#book_img').attr({'src':media_location+'/img/users/nophoto.jpg','width': 96, 'height': 153});          
            
            if(data['error'])
            {
                PopupMessage(I18n[0], data['error']); 
            }
            else
            {
				
                $('input[name=BooksTitle]').val(data['title']);
                $('input[name=Authors]').val(data['author']);
                $('textarea[name=BooksShortText]').val(data['about']);
                $('input[name=PublishingTitle]').val(data['publishing']);
                $('input[name=BooksPublishingYear]').val(data['year']);
                $('input[name=BooksPagesCount]').val(data['pages']);

                elrte.val(data['about']);
                
				//$.wymeditors(0).html(data['about']);

                if(data['genres_all'])
                {
                    $('#genres').val(data['genres_childs']);
                    parents = data['genres_parent'].split(',');
                    for(i = 0;i < parents.length;i++)
                    {
                        GetGenres($('a[Genre='+parents[i]+']'), SelectGenresFromField);
                    }
                }
                if(data['type'])
                {
                    $('select[name=BooksTypesId]').val(data['type']);
                }     
                if(data['cover'])
                {
                    $('select[name=BooksCoversId]').val(data['cover']);
                }
                if(data['weight'])
                {
                    $('input[name=BooksWeight]').val(data['weight']);
                }
                if(data['reprinted'])
                {
                    if(data['reprinted'] == 1)
                    {
                        $('input[name=BooksReprinted]').attr('checked', true);
                    }
                    else
                    {
                        $('input[name=BooksReprinted]').removeAttr('checked');
                    }
                }
                if(data['language'])
                {
                    $('select[name=LanguagesId]').val(data['language']);
                }
                if(data['image'])
                {
                    response = data['image'].split('||'); 
                    
                    $('#book_img').attr({'src':response[0], 'width':response[2], 'height':response[3]});          
                    $('#image_id').val(response[1]);                    
                }
                
                if(type == 'title' && data['isbn']) 
                {
                    $('input[name=BooksISBN]').val(data['isbn']);
                }
                else if(type == 'isbn')
                {
                    $('input[name=BooksISBN]').val(value);
                }
                
                $('#book_search').val('');
                $('#isbn_search').val('');
            }
        }     
        ,'json'          
    );
}


function ChangeBookCount(obj, rowId)
{    
    var bookCount = $(obj).val();
    $(obj).attr('disabled', true); 
    
    $.post(
        http_location + '/basket/changeBookCount',
        {row : rowId, count : bookCount},
        function(data) 
        {
            if(data[0] == 'error')
            {
                PopupMessage(I18n[0], data[1]);  
                return;
            }
            else
            {
				window.location.reload(true);
            }
			
            $(obj).removeAttr('disabled'); 
        },
        'json'      
    ); 
}


function ScrollToFirstErrorField()
{
    var $target = $('html').find('span[class*=error]:eq(0)');
    $('html').stop().scrollTo($target, 0, {offset:-50} );
}

function ChangedDeliveryType()
{
	var value = $('select[name=delivery]').val();
	var price = 0;
	var sum   = parseFloat($('#sum').html());

	$('#tariffsTitle').hide();
	$('table[class=tariffs]').hide();

	$('*[type=with]').hide();

	$('#paymentTitle').hide();
	$('dl[type=payment]').hide();

	if(value == 'Mail')
	{
		$('#tariffsTitle').show();
		$('table[class=tariffs]').show();

		price = parseFloat($('td[class=sel]').html());
	}
	else if(value == 'Courier')
	{
		$('*[type=with]').show();

		$('input[field=deliveryPrice]').each(function()
		{
			price+= parseFloat($(this).val());
		});

		if($('input[name=BasketPayment]').val() == 'Cash')
		{
			$('#paymentTitle').show();
			$('dl[type=payment]').show();
		}
	}
	else if(value == 'Booklist')
	{
		price = parseFloat(booklist_delivery_price * parseFloat($('#private_count').val()));
	}

	sum = (sum + price).toFixed(2);
	
	$('#delivery').html(price.toFixed(2));
	$('#total').html(sum);

	$('input[name=BasketDelivery]').val(value);
	$('input[name=BasketDeliveryPrice]').val(price);
}

function ChangedPaymentType()
{
	var value = $('select[name=payment]').val();

	if(value == 'Cash')
	{
		$('#transferTitle').hide();
		$('dl[class=contacts]').hide();

		if($('input[name=BasketDelivery]').val() == 'Courier')
		{
			$('#paymentTitle').show();
			$('dl[type=payment]').show();
		}
	}
	else
	{
		$('#transferTitle').show();
		$('dl[type=transfer]').show();

		$('#paymentTitle').hide();
		$('dl[type=payment]').hide();
	}

	$('input[name=BasketPayment]').val(value);
}


function overlay()
{
    if(jQuery.support.cssFloat == true)
    {
        $("#bg").fadeIn('fast');
    }
    else
    {
        $("#bg").show();           
        $("#bg").css({
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          height: $(document).height()
        });
    }
}

function forIE6()
{
    if(jQuery.support.cssFloat == false)    
    {
        $('#bg').bgiframe();
        $('div[menu=my]').bgiframe();
        $('.message').bgiframe();
        $('.content form').bgiframe();
    }
}


function showBasketBooks(id, obj)
{
	$('tr[basket='+id+']').toggle();
	
	if($(obj).attr('status') == 1)
	{
		$(obj).css('background-image', '');
		$(obj).attr('status', 0);

		$.cookie('basket_open_' + id, null, null);
	}
	else
	{
		$(obj).css('background-image', 'url('+media_location+'/img/pointer_4b.gif)');
		$(obj).attr('status', 1);

		$.cookie('basket_open_' + id, 'true', {expires: 1, path: '/'});
	}
}

function show(id)
{
	$('#'+id).toggle();
}

function ShowAddressFormUser()
{
	$('#add').show();
	$(document).bind('keydown', 'Esc', function(){CloseMessage('add')} );
	$('#bg').unbind().click(function() {CloseMessage('add')});
	$('a[rel=close]').unbind().click(function() {CloseMessage('add')});

	if (GBrowserIsCompatible())
	{
        geocoder = new GClientGeocoder();

		var loc = $('input[name=UsersAddressGmap]').val().split('|');
		mylat = loc[0];
		mylon = loc[1];

		var map = new GMap2(document.getElementById("private_map"));
		map.enableScrollWheelZoom();
		
		if(mylat == '' || mylon == '')
		{
			map.setCenter(new GLatLng(56.94773153273945, 24.119603633880615), 14);
		}
		else
		{
			var point = new GLatLng(mylat, mylon);
			map.addOverlay(new GMarker(point));
			
			map.setCenter(new GLatLng(mylat, mylon), 16);
		}
		GEvent.addListener(map, "click", function(overlay, latlng)
		{
			var lat = latlng.lat();
			var lon = latlng.lng();

			$('input[name=UsersAddressGmap]').val(lat+'|'+lon);
			
			map.clearOverlays();
			var point = new GLatLng(lat, lon);
			map.addOverlay(new GMarker(point));

			geocoder.getLocations(latlng, function(response)
			{
				place = response.Placemark[0];
				
				$('input[name=UsersAddress]').val(place.address);
				$('input[name=UsersPostIndex]').val('LV'+place.AddressDetails.Country.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber);
			}
			);
		});
	}
}

var form_object = false;
function ShowAddressForm(obj)
{
	$('#new_address_value').val('');
	$('#add select').val('0');
	$('#add select[type=workday]').val('8');
	
	$('#add').show();

	if(obj)
	{
		form_object = obj;
	}

	if (GBrowserIsCompatible())
	{
        geocoder = new GClientGeocoder();

		var map = new GMap2(document.getElementById('juridic_map'));
		map.enableScrollWheelZoom();
		map.setCenter(new GLatLng(56.94773153273945, 24.119603633880615), 14);
		
		GEvent.addListener(map, "click", function(overlay, latlng)
		{
			var lat = latlng.lat();
			var lon = latlng.lng();

			$('#new_address_gmap_value').val(lat+'|'+lon);

			map.clearOverlays();
			var point = new GLatLng(lat, lon);
			map.addOverlay(new GMarker(point));

			geocoder.getLocations(latlng, function(response)
			{
				place = response.Placemark[0];

				$('#new_address_value').val(place.address);
			}
			);
		});
	}

	$(document).bind('keydown', 'Esc', function(){CloseMessage('add')} );
}

function SaveAddress()
{
	var address = $('#new_address_value').val();
	var gmap    = $('#new_address_gmap_value').val();
	
	if(address == '')
	{
		PopupMessage(I18n[0], I18n[1]);
		return false;
	}
	var tmp;
	var workdays_from	= parseInt($('#workdays_from').val());
	var workdays_to		= parseInt($('#workdays_to').val());
	if(workdays_from > workdays_to)
	{
		tmp = workdays_from;
		workdays_from = workdays_to;
		workdays_to = tmp;
	}
	address+= '|' + workdays_from + '-' + workdays_to;
	var saturday_from	= parseInt($('#saturday_from').val());
	var saturday_to		= parseInt($('#saturday_to').val());
	if(saturday_from > 0 && saturday_to > 0)
	{
		if(saturday_from > saturday_to)
		{
			tmp = saturday_from;
			saturday_from = saturday_to;
			saturday_to = tmp;
		}
		address+= '|' + saturday_from + '-' + saturday_to;
	}
	else
	{
		address+= '|-';
	}
	var sunday_from		= parseInt($('#sunday_from').val());
	var sunday_to		= parseInt($('#sunday_to').val());
	if(sunday_from > 0 && sunday_to > 0)
	{
		if(sunday_from > sunday_to)
		{
			tmp = sunday_from;
			sunday_from = sunday_to;
			sunday_to = tmp;
		}
		address+= '|' + sunday_from + '-' + sunday_to;
	}
	else
	{
		address+= '|-';
	}
	var html = '';
	html+= '<dd style="margin-bottom:10px;">';
	html+= '<input type="text" value="' + address + '" style="margin-right:30px;" name="Address[]" />';
	html+= '<input type="hidden" value="' + gmap + '" style="margin-right:30px;" name="AddressGmap[]" />';
	html+= '<a onClick="$(this).parent().remove()" style="cursor:pointer">'+I18n[5]+'</a>';
	html+= '</dd>';

	$('#addresses').append(html)
	if(form_object)
	{
		$('#null_input').remove();
	}

	CloseMessage('add');
	
	return true;
}

function activateTooltips()
{
	$('[title]').tooltip();
}

function resizeIframeToFitContent(iframe)
{
	iframe.height = iframe.contentWindow.document.body.scrollHeight;
	iframe.style.backgroundColor = "transparent";
	iframe.frameBorder = "0";
	iframe.allowTransparency="true";
}

function activateRating()
{
	$('input[name=star]').rating({
		callback: function(value, link)
		{
			$('#wrapper').css('cursor', 'wait');
			
			var type = $(this).attr('rating_type');
			var id   = $(this).attr('rating_id');
			var obj  = $(this);
			$.get(
				http_location + '/rate/' + type + '/' + id + '/' + value,
				function(response)
				{
					$('#wrapper').css('cursor', 'default');						
					
					if(response < 0)
						return;
					
					obj.rating('select', response);
					obj.rating('disable');

					$('#' + type + '_' + id).html(response);
				}
			)
		}
	});
}

function changeSellType(obj)
{
	if($(obj).val() != 'sell')
		$('#SellType').hide();
	else
		$('#SellType').show();
}

function buyEbook(id, price, money)
{
    if(!is_logined)
        PopupMessage(I18n[6], I18n[9])
    else if(price > money)
        PopupMessage(I18n[6], I18n[7])
    else
    {
        overlay();
        
        $('#confirm_message').show();
        $('#confirm_message h2').html(I18n[6]);
        $('#confirm_message label').html(I18n[8]);

        $('#btn_ok').bind('click', function() {
            $('#confirm_message').hide();
            $("#bg").hide();
            window.open(http_location + '/ebook/buy/'+id);
            window.location.reload(true);
        });
        $('#btn_cancel').bind('click', function() {$('#confirm_message').hide();$("#bg").hide();} );
    }
}

function receiveMoney()
{
    overlay();

    $('#receivemoney').show();
}

function checkAgreement(obj, type)
{
    if($(obj).is(':checked'))
    {
        $('#' + type).show();
    }
    else
    {
        $('#' + type).hide();
    }
}

function setSlider()
{
    $("#slider").easySlider({
        prevId:'prevBtn1',
        prevText:'',
        nextId:'nextBtn1',
        nextText:'',
        controlsShow:false
    });
    
    $("#slider").css('width', '961px');
}