$(document).ready(function(){
  var dockOptions =
  { 
     align: 'center',
     size: 112
  };
  var lightboxOptions = 
  {
     imageLoading:         '/img/lightbox/lightbox-ico-loading.gif',
     imageBtnPrev:         '/img/lightbox/lightbox-btn-prev.gif',
     imageBtnNext:         '/img/lightbox/lightbox-btn-next.gif',
     imageBtnClose:         '/img/lightbox/lightbox-btn-close.gif',
     imageBlank:            '/img/lightbox/lightbox-blank.gif',
     txtImage:   'Изображение',
     txtOf:      'из'
  }
//  $('#menu_jqdock').jqDock(dockOptions);
  
  $('#page_gallery a').lightBox(lightboxOptions);    
  $('a.lightbox').lightBox(lightboxOptions);

	$('#photos_gallery a').each(function (){
     	if ($(this).hasClass('hidden'))
        	$(this).hide();
  	});

  	$("div.change_photo").each(function () {
      $(this).click(function () {
         setActImage($(this).attr('rel'));
//         hs.htmlExpand(null, {maincontentText: $("#view_content").html(), width:820, height: 560});
         showViewContent();
      });

      $(this).hover(function () {
         $("div.change_photo_c").each(function () {
            $(this).css('background-color', '#FFFFFF');
         });
         toggleImage($(this).attr('rel'));
         $("#ch_i_"+$(this).attr('rel')).css('background-color', '#F76F01');
      }, function () {});
   });
   $("#ch_i_1").css('background-color', '#F76F01');

   $("a.photo_big").each(function () {
      $(this).click(function () {
         setActImage($(this).attr('rel'));
         showViewContent();
         return false;
      });
   });

   $("#showAllPhotos").click(function () {
      setActImage(6);
      showViewContent();
      return false;
   });

	$("#add_response").click(function() {
		$(".response").each(function(){
			$(this).hide(1000);
		});
		
		$("#add_resp_block").show(1000);
		
		return false;
	});
	$("#add_resp_block").hide();
	
	$("#addResponse").click(function() {		
		if ($('#rank').val()=='0')
		{
			alert('Необходимо выставить оценку товара!');
			return false;
		}
		
		if (!$('#name').val())
		{
			alert('Необходимо указать Ваше имя!');
			$('#name').focus();
			return false;
		}

		if (!$('#city').val())
		{
			alert('Необходимо указать Ваш город!');
			$('#city').focus();
			return false;
		}
		
		if (!$('#person').val())
		{
			alert('Необходимо указать кому делали подарок (другу, подруге, родителям...)!');
			$('#person').focus();
			return false;
		}

		if (!$('#reason').val())
		{
			alert('Необходимо указать повод подарка (День Рождения, Новый Год...)!');
			$('#reason').focus();
			return false;
		}		
		
		if (!$('#title').val())
		{
			alert('Необходимо указать заголовок отзыва!');
			$('#title').focus();
			return false;
		}				
		
		if (!$('#response_text').val())
		{
			alert('Необходимо указать текст отзыва!');
			$('#response_text').focus();
			return false;
		}
		
		// -> add response to db
		$.ajax({
			url: '/items/addresponse',
			type: 'POST',
			dataType: 'text',
			success: function(data) {
				alert(data);
				$("#add_resp_block").hide(1000);
				$(".response").each(function(){
					$(this).show(1000);
				});
				$("#add_response").hide();				
			},
			failure: function() {alert('Произошла ошибка при обработке данных, попробуйте позже.');},
			data: {rank:$("#rank").val(), name: $("#name").val(), city: $("#city").val(), person: $("#person").val(),
					 reason: $("#reason").val(), title: $("#title").val(), response_text: $("#response_text").val(), item_id: $("#item_id").val()}
		});												
	});
	
	$("#cancelResponse").click(function (){
		$("#add_resp_block").hide(1000);
		$(".response").each(function(){
			$(this).show(1000);
		});	
	})
	
	$("#st_5").hover(function(){hover_in_star(5);}, hover_out_star);
	$("#st_4").hover(function(){hover_in_star(4);}, hover_out_star);
	$("#st_3").hover(function(){hover_in_star(3);}, hover_out_star);
	$("#st_2").hover(function(){hover_in_star(2);}, hover_out_star);
	$("#st_1").hover(function(){hover_in_star(1);}, hover_out_star);
	$("#st_5").click(function(){click_star(5)});
	$("#st_4").click(function(){click_star(4)});
	$("#st_3").click(function(){click_star(3)});
	$("#st_2").click(function(){click_star(2)});
	$("#st_1").click(function(){click_star(1)});				
			
	gen_ny_data();
	setTimeout(gen_ny_data, 1000);
	
	$("#ny_header").click(ny_redirect);
	$("#ny_buy").click(ny_redirect);	
	$("#ny_d").click(ny_redirect);
	$("#ny_h").click(ny_redirect);
	$("#ny_i").click(ny_redirect);
	$("#ny_s").click(ny_redirect);
	
	$("div.catalog_item").each(function() {
		$(this).hover(function (){
//			$(this).find('div.catalog_name a').css('text-decoration',  'underline');
			$(this).find('div.catalog_photo').css('border', 'solid 1px #ff6600');
		}, function() {
//			$(this).find('div.catalog_name a').css('text-decoration', 'none');
			$(this).find('div.catalog_photo').css('border', 'solid 1px #dce1e4');			
		});
	});
		
		
	if ($("#bottom_catalog_text").html())
	{
		$("#bottom_catalog_text_show").html($("#bottom_catalog_text").html());
		$("#bottom_catalog_text").html('');
	}	
	
	$("div.gifts_b_l").hover(
		function (){$("#birthday_banner").css('background-image', 'url(/img/birthday/'+$(this).attr('rel')+'.jpg)');},
		function (){$("#birthday_banner").css('background-image', 'url(/img/birthday/def.jpg)');}
	);	

	$("div.gifts_b_l2").hover(
		function (){$("#birthday_banner2").css('background-image', 'url(/img/birthday/bday/'+$(this).attr('rel')+'.jpg)');},
		function (){$("#birthday_banner2").css('background-image', 'url(/img/birthday/bday/def.jpg)');}
	);

    $("div.gifts_b_l3").hover(
		function (){$("#birthday_banner3").css('background-image', 'url(/img/occas/'+$(this).attr('rel')+'.jpg)');},
		function (){$("#birthday_banner3").css('background-image', 'url(/img/occas/occasionsLanding.jpg)');}
	);


    $("div.gifts_b_l3").hover(
		function (){$("#birthday_banner4").css('background-image', 'url(/img/rec/'+$(this).attr('rel')+'.jpg)');},
		function (){$("#birthday_banner4").css('background-image', 'url(/img/rec/recipientsLanding.jpg)');}
	);
    
    $("div.gifts_b_l5").hover(
		function (){$("#birthday_banner5").css('background-image', 'url(/img/spec/'+$(this).attr('rel')+'.jpg)');},
		function (){$("#birthday_banner5").css('background-image', 'url(/img/spec/landing.jpg)');}
	);
    

	$("#addBookmarkText").click(function(){addBookmark();})
	
	// lenta block
	$('#lenta_banner a').lightBox(lightboxOptions); 
/*	$("#move_right").click(function(){
		var offs = $("#lenta_cont").scrollLeft() + 232;
		$("#lenta_cont").animate({scrollLeft: offs}, 1000);
	});
	$("#move_left").click(function(){
		var offs = $("#lenta_cont").scrollLeft() - 232;
		$("#lenta_cont").animate({scrollLeft: offs}, 1000);
	});	
//	$("#lenta_cont").scrollLeft(474);
	$("#lenta_cont").scrollLeft(0);
*/
	// -> responses
	$("div.r_txt").each(function (){
		if ($(this).height() > 72)
		{
			$(this).css('overflow-y', 'hidden');
			$(this).css('height', '72px');
			
			$('#'+$(this).attr('id')+'_').css('visibility', 'visible').css('display', 'block');
		}
	});

   // -> highslide init
   hs.graphicsDir = '/highslide/graphics/';
   hs.outlineType = 'rounded-white';
   hs.wrapperClassName = 'draggable-header';
   hs.fadeInOut = true;
   hs.width = document.body.clientWidth * 0.8;
   hs.height = document.body.clientHeight * 0.9;
   hs.showCredits = false;
   hs.loadingText = 'Загрузка...';
   hs.loadingTitle = 'Кликните мышкой для отмены';
	hs.getAdjacentAnchor = function(op) { return null; };

	$("a.ask_question").click(function(){
		return hs.htmlExpand(this, { objectType: 'ajax', width: 460, height: 380} );
	});

   $("#read_all_but").click(function(){
      if (!document.getElementById('view_bg2'))
      {
         // -> create elements
         var view_bg = "<div id='view_bg2'></div>";
         $('body').append(view_bg);

         var view_obj = '<div id="view_content2"><div id="view_header2">' + view_title + ' - Полное описание<div id="view_close2"></div></div>' +
                        '<div id="view_full_description">' + $("#read_all").html() +'</div>';
         $('body').append(view_obj);

         $("#view_bg2").click(function (){
            $("#view_bg2").hide();
            $("#view_content2").hide();
         });
         $("#view_close2").click(function (){
            $("#view_bg2").hide();
            $("#view_content2").hide();
         });
      }

      $("#view_content2").css('left', ($(window).width() - $("#view_content2").width() > 0 ? $(window).width() - $("#view_content2").outerWidth(): 0)/2 + $(window).scrollLeft() + "px")
                        .css('top', (150 + $(window).scrollTop()) + "px");

   //   $("#view_content").css('left', '100px')
   //                     .css('top', '100px');

      $("#view_bg2").show();
      $("#view_bg2").css('filter', 'alpha(opacity=60)');
      $("#view_content2").fadeIn();

      return false;
   });
});

/*
* Responses funcs
*/
function showResp(id)
{
	$("#resp"+id).css('overflow-y', 'visible');
	$("#resp"+id).css('height', 'auto');	
	$("#resp"+id+"_").hide();
}

function goodResp(id)
{
	$.ajax({
			url: '/items/voteresponse',
			type: 'POST',
			dataType: 'text',
			success: function(data) {
				alert(data);
				$("#rep_p_"+id).hide();
			},
			failure: function() {alert('Произошла ошибка при обработке данных, попробуйте позже.');},
			data: {resp_id:id, dir: 'positive'}
		});
}

function badResp(id)
{
	$.ajax({
			url: '/items/voteresponse',
			type: 'POST',
			dataType: 'text',
			success: function(data) {
				alert(data);
				$("#rep_p_"+id).hide();
			},
			failure: function() {alert('Произошла ошибка при обработке данных, попробуйте позже.');},
			data: {resp_id:id, dir: 'negative'}
		});
}

/*
* Stars functions
*/
function hover_in_star(cur_star)
{		
	for (i=1; i<6; i++)
		if (i<=cur_star)
			$("#st_"+i).css("background-image", "url(/img/star.png)");	
		else
			$("#st_"+i).css("background-image", "url(/img/star_ia.png)");
}

function hover_out_star()
{
	var cur_rank = $("#rank").val();
		
	for (i=1; i<6; i++)
		if (i<=cur_rank)
			$("#st_"+i).css("background-image", "url(/img/star.png)");	
		else
			$("#st_"+i).css("background-image", "url(/img/star_ia.png)");
}

function click_star(cur_star)
{
	$("#rank").val(cur_star);
}

/*
* New Year banner
*/
function gen_ny_data()
{
  	today=new Date();
  	ny_day = new Date(2011, 0, 1);
  	diff = new Date();
  	diff.setTime(ny_day.getTime()-today.getTime());
	$("#ny_d").html(diff.getDate()+"<br /><span style='font-size: xx-small'>день</span>");
	$("#ny_h").html(diff.getHours()+"<br /><span style='font-size: xx-small'>час</span>");
	$("#ny_i").html(diff.getMinutes()+"<br /><span style='font-size: xx-small'>мин</span>");
	$("#ny_s").html(diff.getSeconds()+"<br /><span style='font-size: xx-small'>сек</span>");			
	setTimeout(gen_ny_data, 1000);	
}
function ny_redirect()
{
	location.href = "/new_year";
}

/*
* Change image in photo gallery
*/
function toggleImage(img)
{
  	var i=1;
  	var show_obj=false;
  	var hide_obj=false;
  	$('#photos_gallery a').each(function (){
     	if (i==img)
     	{
        	if ($(this).hasClass('hidden'))
           	show_obj = this;
     	}
     	else
     	{
        	if (!$(this).hasClass('hidden'))
        	{
           	hide_obj = this;
           	$("#ch_i_"+i).removeClass('change_photo_act');
        	}
     	}   
     	i++;
  	});
  
  	if (hide_obj)
  	{
     	$(hide_obj).addClass('hidden');
     	$(hide_obj).hide();
      if (show_obj)
      {
         $(show_obj).removeClass('hidden');
         $(show_obj).show();
      }
  	}
  	$("#ch_i_"+img).addClass('change_photo_act');  
}

var act_img = 1;
var preloaded_images = new Array();
function setActImage(img)
{
   act_img = img;

   if (document.getElementById('view_img'))
   {
      $("div.view_photo_c").each(function () {
         $(this).css('background-color', '#FFFFFF');
      });
      $("#view_i_"+act_img).css('background-color', '#F76F01');

      loadViewImage('http://www.artskills-studio.ru/photos/'+current_item+'/'+act_img+'_big.png');
   }
}

function checkImageForLoad(img_src)
{
   for (i=0; i<preloaded_images.length; i++)
   {
      if (preloaded_images[i] == img_src)
      {
         return true;
      }
   }
   return false;
}

function showViewContent()
{
   if (!document.getElementById('view_bg'))
   {
      // -> create elements
      var view_bg = "<div id='view_bg'></div>";
      $('body').append(view_bg);
      
      $("#view_bg").click(function (){
         hideViewContent();
      });

      var view_obj = '<div id="view_content"><div id="view_header">' + view_title + ' - Все фотографии<div id="view_close"></div></div>' +
                     '<div id="view_list">';

      for (i=0; i< view_photo_list.length; i++)
      {
         view_obj += '<div class="view_photo_c" id="view_i_' + view_photo_list[i] + '"><div class="view_photo" rel="' + view_photo_list[i] + '"">' +
                     '<img src="http://www.artskills-studio.ru/photos/' + current_item +'/' + view_photo_list[i] +'_thumb2.png"/></div></div>';
      }

      view_obj += '</div><div id="view_big"><img id="view_img" src=""/>' +
                  '<div id="view_loading"><img src="/img/lightbox-ico-loading.gif" /></div>'
                  + '<div class="clear"></div></div>';

      $('body').append(view_obj);
      $("#view_i_"+act_img).css('background-color', '#F76F01');

      $("div.view_photo").each(function () {
         $(this).hover(function () {
            setActImage($(this).attr('rel'));
         }, function () {});
      });

      loadViewImage('http://www.artskills-studio.ru/photos/' + current_item + '/' + act_img + '_big.png');

      $("#view_close").click(function (){
         hideViewContent();
      });

      $("#view_img").load(function () {
         if (!checkImageForLoad($(this).attr('src')))
         {
            $("#view_img").show();
            $("#view_loading").hide();
            preloaded_images.push($("#view_img").attr('src'));
         }
      });
   }

   $("#view_content").css('left', ($(window).width() - $("#view_content").width() > 0 ? $(window).width() - $("#view_content").outerWidth(): 0)/2 + $(window).scrollLeft() + "px")
                     .css('top', ($(window).height() - $("#view_content").height() > 0 ? $(window).height() - $("#view_content").outerHeight(): 0)/2 + $(window).scrollTop() + "px");

//   $("#view_content").css('left', '100px')
//                     .css('top', '100px');

   $("#view_bg").show();
   $("#view_bg").css('filter', 'alpha(opacity=60)');
   $("#view_content").fadeIn();
   
}

function loadViewImage(img_src)
{
   if (!checkImageForLoad(img_src))
   {
      $("#view_img").hide();
      $("#view_loading").show();
   }
   $("#view_img").attr('src', img_src);

}

function hideViewContent()
{
   $("#view_bg").fadeOut();
   $("#view_content").fadeOut();
}

function addBookmark(){
		title = "Студия Artskills-Studio"; 
		url = "http://www.artskills-studio.ru";

		if ($.browser.mozilla) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, url,"");
		} else if( $.browser.msie ) { // IE Favorite
			window.external.AddFavorite( url, title); }
		else if($.browser.opera) { // Opera Hotlist
			alert("Для добавления сайта в закладки зажмите Ctrl+T");
			return true; }
		else {
			alert("Для добавления сайта в закладки зажмите Ctrl+D");
			return true; }
}

function doAsk(hide_obj) {
   var nm = $("#ask_name").val();
   var em = $("#ask_email").val();
   var ph = $("#ask_phone").val();
   var ds = $("#ask_desc").val();

   if (!nm)
   {
      alert('Необходимо указать Ваше имя!');
      $("#ask_name").focus();
      return false;
   }

   if (!em)
   {
      alert('Необходимо указать Ваш email!');
      $("#ask_email").focus();
      return false;
   }

   if (!ph)
   {
      alert('Необходимо указать Ваш телефон!');
      $("#ask_phone").focus();
      return false;
   }

   if (!ds)
   {
      alert('Необходимо задать сам вопрос!');
      $("#ask_desc").focus();
      return false;
   }

	$.ajax({
			url: '/items/ask_q',
			type: 'POST',
			dataType: 'text',
			success: function(data) {
				alert(data);
            $("#ask_name").val('');
            $("#ask_email").val('');
            $("#ask_phone").val('');
            $("#ask_desc").val('');
				hs.close(hide_obj);
			},
			failure: function() {alert('Произошла ошибка при обработке данных, попробуйте позже.');},
			data: {item_id:$("#ask_id").val(), name:nm, email:em, phone:ph, description:ds}
		});
}

function getContent(href){
	$.ajax({
		url: href,
		cache: false,
		beforeSend: function() {
			$('#gifts').html('Загрузка подарков...');
		},
		complete: function(html){
			$("#gifts").html(html.responseText);
		}
	});
	return false;
}

