/* Cycle Image Rotator */
(function(D){var A="Lite-1.0";D.fn.cycle=function(E){return this.each(function(){E=E||{};if(this.cycleTimeout){clearTimeout(this.cycleTimeout)}this.cycleTimeout=0;this.cyclePause=0;var I=D(this);var J=E.slideExpr?D(E.slideExpr,this):I.children();var G=J.get();if(G.length<2){if(window.console&&window.console.log){window.console.log("terminating; too few slides: "+G.length)}return }var H=D.extend({},D.fn.cycle.defaults,E||{},D.metadata?I.metadata():D.meta?I.data():{});H.before=H.before?[H.before]:[];H.after=H.after?[H.after]:[];H.after.unshift(function(){H.busy=0});var F=this.className;H.width=parseInt((F.match(/w:(\d+)/)||[])[1])||H.width;H.height=parseInt((F.match(/h:(\d+)/)||[])[1])||H.height;H.timeout=parseInt((F.match(/t:(\d+)/)||[])[1])||H.timeout;if(I.css("position")=="static"){I.css("position","relative")}if(H.width){I.width(H.width)}if(H.height&&H.height!="auto"){I.height(H.height)}var K=0;J.css({position:"absolute"}).hide().each(function(M){D(this).css("z-index",G.length-M)});D(G[K]).css("opacity",1).show();if(D.browser.msie){G[K].style.removeAttribute("filter")}if(H.fit&&H.width){J.width(H.width)}if(H.fit&&H.height&&H.height!="auto"){J.height(H.height)}if(H.pause){I.hover(function(){this.cyclePause=1},function(){this.cyclePause=0})}D.fn.cycle.transitions.fade(I,J,H);J.each(function(){var M=D(this);this.cycleH=(H.fit&&H.height)?H.height:M.height();this.cycleW=(H.fit&&H.width)?H.width:M.width()});J.not(":eq("+K+")").css({opacity:0});if(H.cssFirst){D(J[K]).css(H.cssFirst)}if(H.timeout){if(H.speed.constructor==String){H.speed={slow:600,fast:200}[H.speed]||400}if(!H.sync){H.speed=H.speed/2}while((H.timeout-H.speed)<250){H.timeout+=H.speed}}H.speedIn=H.speed;H.speedOut=H.speed;H.slideCount=G.length;H.currSlide=K;H.nextSlide=1;var L=J[K];if(H.before.length){H.before[0].apply(L,[L,L,H,true])}if(H.after.length>1){H.after[1].apply(L,[L,L,H,true])}if(H.click&&!H.next){H.next=H.click}if(H.next){D(H.next).bind("click",function(){return C(G,H,H.rev?-1:1)})}if(H.prev){D(H.prev).bind("click",function(){return C(G,H,H.rev?1:-1)})}if(H.timeout){this.cycleTimeout=setTimeout(function(){B(G,H,0,!H.rev)},H.timeout+(H.delay||0))}})};function B(J,E,I,K){if(E.busy){return }var H=J[0].parentNode,M=J[E.currSlide],L=J[E.nextSlide];if(H.cycleTimeout===0&&!I){return }if(I||!H.cyclePause){if(E.before.length){D.each(E.before,function(N,O){O.apply(L,[M,L,E,K])})}var F=function(){if(D.browser.msie){this.style.removeAttribute("filter")}D.each(E.after,function(N,O){O.apply(L,[M,L,E,K])})};if(E.nextSlide!=E.currSlide){E.busy=1;D.fn.cycle.custom(M,L,E,F)}var G=(E.nextSlide+1)==J.length;E.nextSlide=G?0:E.nextSlide+1;E.currSlide=G?J.length-1:E.nextSlide-1}if(E.timeout){H.cycleTimeout=setTimeout(function(){B(J,E,0,!E.rev)},E.timeout)}}function C(E,F,I){var H=E[0].parentNode,G=H.cycleTimeout;if(G){clearTimeout(G);H.cycleTimeout=0}F.nextSlide=F.currSlide+I;if(F.nextSlide<0){F.nextSlide=E.length-1}else{if(F.nextSlide>=E.length){F.nextSlide=0}}B(E,F,1,I>=0);return false}D.fn.cycle.custom=function(K,H,I,E){var J=D(K),G=D(H);G.css({opacity:0});var F=function(){G.animate({opacity:1},I.speedIn,I.easeIn,E)};J.animate({opacity:0},I.speedOut,I.easeOut,function(){J.css({display:"none"});if(!I.sync){F()}});if(I.sync){F()}};D.fn.cycle.transitions={fade:function(F,G,E){G.not(":eq(0)").css("opacity",0);E.before.push(function(){D(this).show()})}};D.fn.cycle.ver=function(){return A};D.fn.cycle.defaults={timeout:4000,speed:1000,next:null,prev:null,before:null,after:null,height:"auto",sync:1,fit:0,pause:0,delay:0,slideExpr:null}})(jQuery)

/* Coockie */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function b_statistic(){
    $.ajax({
      type: 'POST',
      url: '/ajax/slot_click_count/',
      data: {'click':'b34ed079884844cdc8ce331c506df36f'}
    });
}

function ajax_send(){
    $.ajax({
      type: 'POST',
      url: '/ajax/letter/',
      data: {'type':'o'},
      dataType: 'json',
      success: function(msg)
      {
        $('.k_3').css({'background':'url('+msg.image+') no-repeat center'});
        $('.k_3 .outoff p').html(msg.text);
        $('.k_3 .link').attr('href', msg.portfolio);
      }
    });
    $.ajax({
      type: 'POST',
      url: '/ajax/letter/',
      data: {'type':'e'},
      dataType: 'json',
      success: function(msg)
      {
        $('.k_5').css({'background':'url('+msg.image+') no-repeat center'});
        $('.k_5 .outoff p').html(msg.text);
        $('.k_5 .link').attr('href', msg.portfolio);
      }
    });
}

function set_offset(){
    var page_width = $('#wrapper').width();  /* Размер окна */
    var elem_q = $('#big_carousel ul.bc_lenta > li').length; /* Количество элементов */
    var elem_width = $('#big_carousel ul.bc_lenta > li').width(); /* Размер одного элемента */
    var car_width = elem_q * elem_width;  /* Вычисляем ширину ленты элементов */
    $('#big_carousel ul.bc_lenta').width(car_width); /* Устанавливаем ширину ленты элементов */
}

//dawron changes
 $(document).ready(function() {
 //Opera overflow hack
    if ($.browser.opera ) {
        $("body, html, #wrapper").css({'position':'absolute', 'overflowX':'auto', 'overflowY':'auto'});
        $("#wrapper").css({'paddingLeft':'5%', 'overflow':'hidden'});
    }
     if ($.browser.opera && $.browser.version == 9.64) {
        $("#ajaxSearch_form, .s_map").css({'top':3+'px'});
        $(".s_link sup").css({'left':0});
    }
  });
//End dawron changes


/* Big Krasota FadeIn/FadeOut on Change */

function fadeIn(){
	$('#k_list .k_3, #k_list .k_5').children('.img_wrap').fadeIn(500);
	$('.change_icons').fadeOut(500);
	$('#k_list .outoff').hide();
}
function fadeOut(){
	$('#k_list .k_3, #k_list .k_5').children('.img_wrap').delay(5000).fadeOut(1000);
	$('.change_icons').delay(7000).fadeIn(500);
	$('#k_list .outoff').delay(5000).fadeIn(500);
}


$(document).ready(function(){

    if (jQuery.browser.msie && jQuery.browser.version == 7 || jQuery.browser.msie && jQuery.browser.version == 6) {
        var el_width = 0;
        var ul_width = 0;
        $('#h_menu a.active').width($('#h_menu a.active span').width());
        $('#h_menu ul li').each(function(){
            el_width = el_width + $(this).width();
        });
        $('#h_menu ul, #h_menu').width(el_width - 26+'px');
//        $('.h_menu ul > li').each(function(){
//            ul_width = ul_width + $(this).width();
//            $(this).parent().parent().width(ul_width);
//        });
    }


    /* Show/Hide input hints */
    $('.block input').focus(function(){
        if($(this).val() == 'contact@cooper-design.com.ua' || $(this).val() == '048777665'){
        this_val = $(this).val();
        $(this).attr('rel', this_val);
        $(this).val('');
    } });
    $('.block input').blur(function(){
        if($(this).val() == ''){
            old_val = $(this).attr('rel');
            $(this).val(old_val);
        }
    });

    /* Order Form */
    $('.b_next').click(function(){
        $(this).parent().parent().hide().next().show();
        $('.ph_list li.'+$(this).parent().parent().next().attr('id')+' a').addClass('active').parent().siblings().find('a').removeClass('active');
    });

    /* BreadCrumbs Actions */
    $('.B_crumbBox li:last').css({'background':'none'});
    $('.b_cont').click(function(){
        return false;   
    });

    $('.b_cont span').click(function(){
        window.location = $(this).parent().attr('href');
    });

    $('.b_cont .e_r').click(function(){
        if($(this).parent().hasClass('closed')){
            $(this).parent().next().show().parent().siblings().find('a.opened').removeClass('opened').addClass('closed').next().hide();
            $(this).parent().removeClass('closed').addClass('opened');
        }
        else if($(this).parent().hasClass('opened')){
            $(this).parent().next().hide();
            $(this).parent().delay(2000).removeClass('opened').addClass('closed');
        }
    });

    /* Change Portfolios List View */
    $('.list_style').click(function(){
        $('.site_shot').addClass('compact');
        $.cookie('portfolio_list_type', 'by_list');
    });
    $('.full_style').click(function(){
        $('.site_shot').removeClass('compact');
        $.cookie('portfolio_list_type', 'by_images');
    });

    /* Article Tabs */
    if($('.a_tabs')){
        var dgfsd = $('.a_tabs_content li').hide();
        for(var k=0; k<$('.a_tabs ul li').length; k++){
            $('.a_tabs li:eq('+k+'), .a_tabs_content li:eq('+k+')').addClass('at_'+k+'');
        }
        var ac_tab = $('.a_tabs li a.active').parent().attr('class');
        $('.a_tabs_content li.'+ac_tab+'').show();
        $('.a_tabs li').click(function(){
            $(this).children('a').addClass('active').parent().siblings().children('a').removeClass('active');
            var clickd = $(this).attr('class');
            $('.a_tabs_content li.'+clickd+'').show().siblings().hide();
            return false;
        });
    }

    /* Left Tabs on Main Page */
    if($('.d_tabs')){
        $('.d_tabs li a.active').parent().parent().siblings().hide();
        var active_tab = $('.d_tabs li a.active').parent().parent().attr('class');
        $('.d_tabs_content li.'+active_tab+'').show().siblings().hide();
        $('.d_tabs li a').click(function(){
            $(this).removeClass('active').parent().parent().siblings().find('a').addClass('active');
            $(this).parent().parent().hide().siblings().show();
            var clicked_tab = $(this).parent().parent().attr('class');
            $('.d_tabs_content li.'+clicked_tab+'').hide().siblings().show();
            return false;
        });
    }

    $('.pagination a span').each(function(){
        if($(this).html() == $.cookie('sel_year')){$(this).parent().addClass('active').parent().siblings().find('a').removeClass('active');}
    });
    $('.pagination a').click(function(){
        $(this).addClass('active').parent().siblings().children('a').removeClass();
        var t_val = $(this).find('span').html();
        $.cookie('sel_year',t_val);
    });

    /* Popup Tabs */
    $('.win').hide();
    if($('.ph_list a.active')){
        var act_li = $('.ph_list a.active').parent().attr('class');
        $('#'+act_li+'').show();
    }

    /* Main Menu Decoration */
    $('#h_menu li a:first').css({'marginLeft':2+'px'});
    $('#h_menu li a:last').css({'marginRight':2+'px'});


    /* Carousel */
    $(window).bind('resize', function() {
        set_offset();
        set_sizes();
        correct_left();
    });
    carousel = $('div.carousel_h ul.elements');
    carousel_item = $('div.carousel_h ul.elements li.c_item');
    $('div.carousel_h ul.elements li.c_item:first').addClass('curent');

    for(var i=0; i<carousel_item.length; i++){
        carousel_item.eq(i).attr('rel',i);
    }

    function set_sizes(){
        win_width = $('#wrapper').width(); // Window Width
        el_width = win_width/2; // Carousel Element Width (50%)
        el_length = $('li.c_item').length; // Carousel Element Length
        c_width = el_length * el_width; // Carousel Width
        carousel.width(c_width);
        carousel_item.width(el_width);
    }
    function correct_left(){
        cur_num = $('li.curent').attr('rel');
        if(cur_num > 0){
            c_left = cur_num * el_width;
            carousel.css('left',-c_left+'px');
        }
        else {return false;}
    }
    function move_left(){
        cur_left_temp = carousel.css('left');
        cur_left = parseInt(cur_left_temp.replace('px',''));
        carousel.stop().animate({left:cur_left - el_width + 'px'});
        $('li.curent').next('li').addClass('curent').prev('li').removeClass('curent');
    }
    function move_right(){
        cur_left_temp = carousel.css('left');
        cur_left = parseInt(cur_left_temp.replace('px',''));
        carousel.stop().animate({left:cur_left + el_width + 'px'});
        $('li.curent').prev('li').addClass('curent').next('li').removeClass('curent');

    }
    function hide_arrow(){
        if($('div.carousel_h ul.elements li.c_item:first').hasClass('curent')){
            $('.c_arrow_left').hide();
        }
        else{$('.c_arrow_left').show();}
        if($('div.carousel_h ul.elements li.c_item:last').hasClass('curent')){
            $('.c_arrow_right').hide();
        }
        else{$('.c_arrow_right').show();}
    }
    function action_feed(){
        var cur_rel = $('li.curent').attr('rel');
        $('.h_menu li.h_'+cur_rel+' a').addClass('active').parent().siblings().find('a').removeClass('active');
    }
    $('.hands .c_arrow_right').click(function(){
        $(this).stop().animate({top:-2000+'px'}, 0).delay(500).animate({top:126+'px'}, 0);
        set_sizes();
        move_left();
        action_feed();
        hide_arrow();
    });
    $('.hands .c_arrow_left').click(function(){
        $(this).stop().animate({top:-2000+'px'}, 0).delay(500).animate({top:126+'px'}, 0);
        set_sizes();
        move_right();
        action_feed();
        hide_arrow();
    });
    set_sizes();
    hide_arrow();

    /* Hands */
    if($('.h_hands')){
        for(var l=0; l<$('.h_hands li').length; l++){
            $('.h_hands li:eq('+l+')').addClass('h_'+l+'');
        }
        $('.h_hands li').click(function(){
            set_sizes();
            var el_num_tmp = $(this).attr('class');
            var el_num = el_num_tmp.replace('h_','');
            $('.carousel_h li.c_item[rel='+el_num+']').addClass('curent').siblings().removeClass('curent');
            cur_num = $('li.curent').attr('rel');
            if(cur_num >= 0){
                c_left = cur_num * el_width;
                carousel.animate({left:-c_left+'px'});
            }
            else {return false;}
            hide_arrow();
        });
    }

    /* Hands */
    if($('.h_numbers')){
        for(var m=0; m<$('.h_numbers li').length; m++){
            $('.h_numbers li:eq('+m+')').addClass('h_'+m+'');
        }
        $('.h_numbers li').click(function(){
            set_sizes();
            var el_num_tmp = $(this).attr('class');
            var el_num = el_num_tmp.replace('h_','');
            $('.carousel_h li.c_item[rel='+el_num+']').addClass('curent').siblings().removeClass('curent');
            cur_num = $('li.curent').attr('rel');
            if(cur_num >= 0){
                c_left = cur_num * el_width;
                carousel.animate({left:-c_left+'px'});
            }
            else {return false;}
            hide_arrow();
        });
    }

    /* Button HOver Events */
    $('.button').hover(
            function(){$(this).css({backgroundPosition:'0 -30px'});},
            function(){$(this).css({backgroundPosition:'0 0'});}
    );

    /* Styling Page's Top Menu Last Element */
    $('.h_menu').each(function(){
        $(this).find('li:last').css({margin:'0'});
    });

    /* Making Page Top Menu Active on Click */
    menu_el = $('.h_menu ul li a');
    menu_el.click(function(){
        $(this).addClass('active').parent().siblings().children('a').removeClass('active');
    });

    /* Contacts Menu Tabs */
    if($('.m_contacts a.active')){
        var act_t = $('.m_contacts a.active').parent().attr('id');
        $('.branches_data li.'+act_t+'').show().siblings().hide();
        $('.m_contacts a').click(function(){
            var clckd_t = $(this).parent().attr('id');
            $('.branches_data li.'+clckd_t+'').show().siblings().hide();

        });
    }

    /* Clear Input */
    $('.block input[type="text"]').focus(function(){
        $(this).next('span.clean').show();
    });
    $('.block input[type="text"]').blur(function(){
        if($(this).val() == ""){$(this).next('span.clean').hide();}
        if($(this).val() != ""){$(this).next('span.clean').show();}
    });
    $('.i_block .clean').click(function(){
        $(this).prev().val('');
    });

    /* Show/Hide Inputs */
    $('.i_block .tab_2').click(function(){
        $(this).parent().parent().addClass('hidden');
        $('.tab_1').parent().parent().removeClass('hidden');
    });
    $('.i_block .tab_1').click(function(){
        $(this).parent().parent().addClass('hidden');;
        $('.tab_2').parent().parent().removeClass('hidden');
    });

    /* Show/Hide Label Text on Focus & Blur */
    $('.search_wrap .s_inp').focus(function(){
        $(this).css({'color':'black'});
        $(this).next().css({'backgroundPosition':'0 -29px'});
        if($(this).val() == 'Поиск'){
            this_val = $(this).val();
            $(this).attr('rel', this_val);
            $(this).val('');
        }
        else{return false;}
    });
    $('.search_wrap .s_inp').blur(function(){
        $(this).next().css({'backgroundPosition':'0 0'});
        if($(this).val() == ''){
            old_val = $(this).attr('rel');
            $(this).val(old_val);
        }
        else{return false;}
    });

    /* Search Field Auto Complete */
    $('.show_popup').click(function(){
        var ex_text = $(this).html();
        $(this).parent().prev().prev().val(ex_text);
        $('.fixed').show();
    });

    $('.fixed a.close').click(function(){
        $('.fixed').hide();
    });

    /* Tabs */
    if($('.city_tabs a.active')){
        var cur_tab = $('.city_tabs a.active').parent().attr('id');
        $('.tabs_content li.'+cur_tab+'').show();
    }
    $('.city_tabs li').click(function(){
        $(this).children('a').addClass('active').parent().siblings().children('a').removeClass('active');
        var clckd_tab = $(this).attr('id');
        $('.tabs_content li.'+clckd_tab+'').fadeIn(500).siblings().fadeOut(500);
    });

    /* Preloader */
    img_wrap = $('#k_list div.img_wrap');
    back = $('#k_list sub.back');
    link = $('#k_list a.link');
    outoff = $('#k_list div.outoff');
    back.animate({
        height:98+'%'
    }, 10000, function(){
        img_wrap.fadeOut(2000);
        link.fadeIn(1500);
        outoff.fadeIn(1500);
        ajax_send();
    });

    /* Carousels */
	
    $(".car_wrap").jCarouselLite({
		btnNext: ".car_right",
		btnPrev: ".car_left",
		visible: 1,
		start: $('.site_shot').length - 1,
        speed:1000
	});

    for(var j=1; j<$('.carousel_wrapper').length + 1; j++){
        if($('#c_'+j+' .carousel_wrapper li').length > 1){
            $("#cr_"+j+", #cl_"+j+"").show();
            $('#c_'+j+' .carousel_wrapper').addClass('cw_'+j+'');
            $(".cw_"+j+"").jCarouselLite({
                btnNext: "#cr_"+j+"",
                btnPrev: "#cl_"+j+"",
                visible: 1,
                speed:1000
            });
        }
    }

	/* Change Icons */
    $('.change_icons').click(function(){
		fadeIn();
        ajax_send();
        fadeOut();
    });
/*
    var category = $('.cat_menu a.active span').html();
	var year = $('.pagination a.active span').html();
    if(category == 'Все категории'){category = 'null';}
	$.ajax({
		type: 'POST',
		url: '/ajax/port',
		data: {'year':year, 'category':category},
		success: function(msg)
		{
			$('.portfolio').html(msg);
            var list_type = $.cookie('portfolio_list_type');
            if(list_type == 'by_images'){$('.full_style').addClass('active'); $('.list_style').removeClass('active'); $('.site_shot').removeClass('compact');}
            if(list_type == 'by_list'){$('.full_style').removeClass('active'); $('.list_style').addClass('active'); $('.site_shot').addClass('compact');}
		}
	});
*/
	$('.pagination a').click(function(){
        $(this).addClass('active').parent().siblings().children('a').removeClass();
		var year = $(this).find('span').html();
		var category = $('.cat_menu a.active span').html();
        if(category == 'Все категории'){category = 'null';}
		$.ajax({
			type: 'POST',
			url: '/ajax/port',
			data: {'year':year, 'category':category},
			success: function(msg)
			{
				$('.portfolio').html(msg);
                var list_type = $.cookie('portfolio_list_type');
                if(list_type == 'by_images'){$('.full_style').addClass('active'); $('.list_style').removeClass('active'); $('.site_shot').removeClass('compact');}
                if(list_type == 'by_list'){$('.full_style').removeClass('active'); $('.list_style').addClass('active'); $('.site_shot').addClass('compact');}
			}
		});
    });

    /* Contact Tab */
    if($('.win_wrapper')){$('.win_wrapper #'+$('.ph_list li:first').attr("class")+'').show().siblings().hide();}    
    $('.ph_list li').click(function(){
        $('.win_wrapper #'+$(this).attr("class")+'').show().siblings().hide();
    });
	
	/* Replacing Some Content */
	if($('.full-w')){
		$('.full-w').insertAfter($('.full-w').parent().prev().find('.p_image'));
	}
	
});
