﻿var active_acordion_tab = 0;

var Header = function()
{
    var animation_state = false;
    var active_tab = 0;
    var active_menu = 0;
    var timer = null;
    var click_element = null;

    this.Init = function()
    {
       var active = $('a[submenu=true].active');

       if(active.length > 0)
       {
          active_menu = $(active).attr('tab');
          active_tab = active_menu;

          var image = $('#headTab'+active_tab);
          $(image).animate({opacity: 1},1000);
       }

       if(active_menu == 0)
       {
           $('#headSlider').nivoSlider(
           {
              effect    : 'sliceDownRight',
              pauseTime :  5000
           });
       }

       $('a[submenu=true]').mouseenter(function()
       {
           if($(click_element).length > 0)
            return false;

           active_tab = $(this).attr('tab');

           if(timer != null)
            timer.stop();

           if(!animation_state && active_tab > 0)
           {
              timer = $.timer(show,500);
              timer.play();
           }
       });

       $('a[submenu=true]').mouseleave(function()
       {
           if($(click_element).length > 0)
            return false;
           
           if(timer != null)
            timer.stop();

           if(!animation_state && active_tab > 0)
           {
             timer = $.timer(hide,500);
             timer.play();
           }
       });

       $('a[submenu=true]').click(function()
       {
           if(animation_state)
           {
             if(timer != null)
                timer.stop();

             click_element = $(this);
             timer = $.timer(click_el,100);
             timer.play();

             return false;
           }
       });
    }

    var hide = function()
    {
      var show_image = $('div[id^=headTab]:visible');
      animation_state = true;

      if(active_menu == 0)
      {
          if(show_image.length > 0)
          {
              $(show_image).animate({opacity: 0.3}, 200,function()
              {
                 show_image.css('display','none');
                 animation_state = false;

                 var header_slider = $('#headSlider:hidden');

                 if(header_slider.length > 0)
                 {
                    $(header_slider).css('display','block');
                 }
              });
          }
          else
          {
              animation_state = false;
              var header_slider = $('#headSlider:hidden');

              if(header_slider.length > 0)
              {
                 $(header_slider).css('display','block');
              }
          }
      }
      else
      {
         var image = $('#headTab'+active_menu);

         if(active_tab != active_menu || image.attr('id') != show_image.attr('id'))
         {
            active_tab = active_menu;
             
            $(show_image).animate({opacity: 0.3}, 200,function()
            {
                 show_image.css('display','none');

                 if(image.length > 0 && !$(image).is(':visible'))
                 {
                    image.css('display','block');

                    $(image).animate({opacity: 1},200,function()
                    {
                       animation_state = false;
                    });
                 }
            });
         }
         else
         {
            animation_state = false;
         }
      }
    }

    var show = function()
    {
      var show_image = $('div[id^=headTab]:visible');
      var image = $('#headTab'+active_tab);
      animation_state = true;

      if(active_menu == 0)
      {
          var header_slider = $('#headSlider:visible');

          if(header_slider.length > 0)
          {
              $(header_slider).css('display','none');
          }
      }

      if(show_image.length > 0)
      {
          if(image.attr('id') != show_image.attr('id'))
          {
              $(show_image).animate({opacity: 0.3}, 200,function()
              {
                 show_image.css('display','none');

                 if(image.length > 0 && !$(image).is(':visible'))
                 {
                    image.css('display','block');
                    $(image).animate({opacity: 1},200,function()
                    {
                       animation_state = false;
                    });
                 }
              });
          }
          else
          {
              animation_state = false;
          }
      }
      else
      {
          if(image.length > 0 && !$(image).is(':visible'))
          {
            image.css('display','block');
            $(image).animate({opacity: 1},200,function()
            {
               animation_state = false;
            });
          }
      }
    }

    var click_el = function()
    {
        if($(click_element).length > 0 && !animation_state)
        {
            timer.stop();
            window.location = $(click_element).attr('href');
        }
    }
}

var gallery = function()
{
    var animate_state = false;

    this.show = function(img)
    {
        var container = $('div[gallery_container=true]');
        var big_img_link = $(container).find('a');
        var img_prew = $(container).find('img');
        var show_img = $(img);
        var show_img_src = '/thumbnail/' + $(show_img).attr('gallery_item_id') + "_507_379";
      
        if(big_img_link.length > 0 && img_prew.length > 0 && !animate_state && $(img_prew).attr('src') != show_img_src)
        {
            animate_state = true;

            $(img_prew).animate({opacity: 0},100,function()
            {
               $(img_prew).attr('src',show_img_src);
               $(big_img_link).attr('href','/getmedia/' + $(show_img).attr('gallery_item_id'));
               $(img_prew).bind('load',{},function(e)
               {
                   $(img_prew).unbind('load');
                   $(img_prew).animate({opacity: 1},100,function()
                   {
                     animate_state = false;
                   });
               });
            });
        }
    }
}


var video = function()
{
    this.show = function(img)
    {
        $('div.videoContainer').html('<object width="640" height="480"><param name="movie" value="'+ $(img).attr('video_url')+'"></param><embed src="'+ $(img).attr('video_url')+'"type="'+ $(img).attr('video_type')+'" width="640" height="480"></embed></object>');
        $('#video_name').html($(img).attr('title'));
        $('#video_content').html($(img).next().html());
    }
}

$(document).ready(function()
{
    $('div.bgShadow').css('display','block');

    $("#inputDateIn1").datepicker(
    {
        showButtonPanel: true,
        showOn: "button",
        buttonImage: "/img/ical.png",
        buttonImageOnly: true,
        dateFormat: 'dd.mm.yy',
        minDate: new Date(),
        showAnim: 'clip'
    });

    $("#inputDateIn2").datepicker({
        showButtonPanel: true,
        showOn: "button",
        buttonImage: "/img/ical.png",
        buttonImageOnly: true,
        dateFormat: 'dd.mm.yy',
        minDate: new Date(),
        showAnim: 'clip'
    });

    if($('div[id=wrapper].properties').length == 0)
    {
        header_obj = new Header();
        header_obj.Init();
    }
    
    $(".advSearch").click(function()
    {
          $(".search2").toggle();
          $(".search1").toggle();
    });

    jQuery('.subMenuCarousel').jcarousel({
        scroll: 1,
        auto: 0,
        buttonNextHTML: '<div class="scrollArrowRight"></div>',
        buttonPrevHTML: '<div class="scrollArrowLeft"></div>'
    });

    var params = {
        changedEl: ".contactSelect select",
        visRows: 5,
        scrollArrows: true
    }
    
    cuSel(params);

    $("#accordionRegions").accordion({autoHeight: false,active : active_acordion_tab});

    $('#banner1').nivoSlider(
    {
        effect              : 'sliceDownRight',
        pauseTime           :  8000,
        directionNav        : true,
        directionNavHide    : false,
        afterChange         : function()
        {
            current_slide_no = jQuery('#banner1').data('nivo:vars').currentSlide;
            jQuery('#banner1-status > .current-slide').html(current_slide_no+1);
        }

    });

    $('#banner2').nivoSlider(
    {
        effect            : 'sliceDownRight',
        pauseTime         :  11000,
        directionNav      : true,
        directionNavHide  : false,
        afterChange       : function()
        {
            current_slide_no = jQuery('#banner2').data('nivo:vars').currentSlide;
            jQuery('#banner2-status > .current-slide').html(current_slide_no+1);
        }
    });

    $(function()
    {
	    $("#tabsSearhFeedback").tabs({ selected: 0 });
	});

    $(function()
    {
		$("#tabsStart1").tabs({ selected: 0 });
	});

    $(function()
    {
		$("#tabsStart2").tabs({ selected: 0 });
	});

    $(function()
    {
		$("div[tab=true]").tabs({ selected: 0 });
	});

    $("#accordionPage").accordion({ autoHeight: false});
          jQuery('#propertiesCarousel').jcarousel({
            scroll: 1,
            auto: 5,
            wrap: 'both'
    });

    jQuery('#openPropertyCarousel').jcarousel({
       scroll: 1,
       wrap: 'both'
    });

    if($('#news_left_block').length > 0)
    {
        setTimeout(function()
        {
            syncBlock();
        },100);
    }

    if($("span[gallery_item=true]").length > 0)
    {
        gallery_obj = new gallery;
    }

    $("span[gallery_item=true]").click(function()
    {
        gallery_obj.show($(this));
    });

    if($("img[id^=video_item_]").length > 0)
    {
        video_obj = new video;
    }

    $("img[id^=video_item_]").click(function()
    {
        video_obj.show($(this));
    });

    $("#currencies").change(function()
    {
        window.location = '/change_currency/' + $(this).val();
    });

    $("select[dinamic_select=region_property]").attr('disabled',false);

    $("select[dinamic_select=region_property]").change(function()
	{
		load_reference_items($(this));
	});

    $("input.findInput").focus(function()
	{
        if($(this).val() == 'Поиск по сайту')
		    $(this).val('');
	});

    $("input.findInput").blur(function()
	{
        if($(this).val() == '')
		    $(this).val('Поиск по сайту');
	});

    $("input[toogle_value=true]").focus(function()
	{
       if($(this).val() == $(this)[0].defaultValue)
       {
           $(this).val('');
           $(this).css('color','#000000');
       }
    });

    $("input[toogle_value=true]").blur(function()
	{
      if($(this).val() == '')
      {
        $(this).val($(this)[0].defaultValue);
        $(this).css('color','#999999');
      }
    });

    jQuery('#videoCarousel').jcarousel({
       scroll   : 1,
       wrap     : 'both'
    });

});

function load_reference_items(input)
{
    var dependent = $(input).attr('child_dinamic_select');
    var default_option = null;
    var region_id = $(input).val();

    default_option = $('select[dinamic_select='+ dependent +']' + " option:first");
    dependent = $('select[dinamic_select='+ dependent +']');

    $(dependent).empty();
    $(dependent).prepend(default_option);

    $(input).attr('disabled','disabled');
    $(dependent).attr('disabled','disabled');

    $.ajax(
    {
        url			 : '/ajax_gate',
        data		 : {loader : 'get_reference_items', ref : 'cities', params : '{"obtain_content" : "true"}'},
        type		 : "POST",
        dataType     : "json",
        success	     : function (data, textStatus)
        {
            $(input).removeAttr('disabled');
            $(dependent).removeAttr('disabled');

            if(data.status && data.data.items.length > 0)
            {
                $.each(data.data.items,function(i, val)
                {
                    if(val.data[0].content == region_id || region_id == 0)
                    {
                        $(dependent).append($('<option value='+ val.id +'>'+ val.name +'</option>'));
                    }
                });
            }
        }
    });
}

function syncBlock()
{
    var left_column_height = $('#sideLeft').height();
    var content_column = $('#content').height() - 45;

    if(left_column_height > content_column)
    {
        var sub_var = Math.floor((left_column_height - content_column) / 48);
        var blog_item_count = $('div.blogItem').length;
        var news_item_count = $('div.newsItem').length;
        var public_item_count = $('div.publicItem').length;

        if(sub_var > 0 && blog_item_count > 3)
        {
            var begin_hide_blogs = blog_item_count - sub_var;

            if(begin_hide_blogs < 3)
                begin_hide_blogs = 3;

            $('div.blogItem').each(function(n,element)
            {
                if(n >= begin_hide_blogs)
                {
                    $(element).css('display','none');
                }
            });
        }

        if(sub_var > 0 && news_item_count > 3)
        {
            var begin_hide = news_item_count - sub_var;

            if(begin_hide < 3)
                begin_hide = 3;

            if(begin_hide > begin_hide_blogs)
                begin_hide = begin_hide_blogs;

            $('div.newsItem').each(function(n,element)
            {
                if(n >= begin_hide)
                {
                    $(element).css('display','none');
                }
            });
        }

        if(sub_var > 0 && public_item_count > 3)
        {
            var begin_hide = public_item_count - sub_var;

            if(begin_hide < 3)
                begin_hide = 3;

            if(begin_hide > begin_hide_blogs)
                begin_hide = begin_hide_blogs;

            $('div.publicItem').each(function(n,element)
            {
                if(n >= begin_hide)
                {
                    $(element).css('display','none');
                }
            });
        }
    }
}

(function($) {
	$.timer = function(func, time, autostart) {
	 	this.set = function(func, time, autostart) {
	 		this.init = true;
	 	 	if(typeof func == 'object') {
		 	 	var paramList = ['autostart', 'time'];
	 	 	 	for(var arg in paramList) {if(func[paramList[arg]] != undefined) {eval(paramList[arg] + " = func[paramList[arg]]");}};
 	 			func = func.action;
	 	 	}
	 	 	if(typeof func == 'function') {this.action = func;}
		 	if(!isNaN(time)) {this.intervalTime = time;}
		 	if(autostart && !this.active) {
			 	this.active = true;
			 	this.setTimer();
		 	}
		 	return this;
	 	};
	 	this.once = function(time) {
			var timer = this;
	 	 	if(isNaN(time)) {time = 0;}
			window.setTimeout(function() {timer.action();}, time);
	 		return this;
	 	};
		this.play = function(reset) {
			if(!this.active) {
				if(reset) {this.setTimer();}
				else {this.setTimer(this.remaining);}
				this.active = true;
			}
			return this;
		};
		this.pause = function() {
			if(this.active) {
				this.active = false;
				this.remaining -= new Date() - this.last;
				this.clearTimer();
			}
			return this;
		};
		this.stop = function() {
			this.active = false;
			this.remaining = this.intervalTime;
			this.clearTimer();
			return this;
		};
		this.toggle = function(reset) {
			if(this.active) {this.pause();}
			else if(reset) {this.play(true);}
			else {this.play();}
			return this;
		};
		this.reset = function() {
			this.active = false;
			this.play(true);
			return this;
		};
		this.clearTimer = function() {
			window.clearTimeout(this.timeoutObject);
		};
	 	this.setTimer = function(time) {
			var timer = this;
	 	 	if(typeof this.action != 'function') {return;}
	 	 	if(isNaN(time)) {time = this.intervalTime;}
		 	this.remaining = time;
	 	 	this.last = new Date();
			this.clearTimer();
			this.timeoutObject = window.setTimeout(function() {timer.go();}, time);
		};
	 	this.go = function() {
	 		if(this.active) {
	 			this.action();
	 			this.setTimer();
	 		}
	 	};

	 	if(this.init) {
	 		return new $.timer(func, time, autostart);
	 	} else {
			this.set(func, time, autostart);
	 		return this;
	 	}
	};
})(jQuery);
