// KADO.RU
var curcity = 341;
var page_left = "";
open_news = 0;
open_vac = 0;
open_inst = 0;

current_menu = "";

function gup( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return false;
    else
        return results[1];
}


function news_show(id){
    elementClick = id + "_full";
    $(elementClick).show();
    $(id + "_short").hide();
    destination = $(elementClick).offset().top;
    if($.browser.safari){
        $('body').animate( {
            scrollTop: destination
        }, 1100 );
    }else{
        $('html').animate( {
            scrollTop: destination
        }, 1100 );
    }
}

function map_init(){
    $('.karta_in:visible').each(function(){
        var id  = $(this).attr('id');
        //alert(id);
        YMaps.load(function(){
            var map = new YMaps.Map(YMaps.jQuery("#"+id)[0]);
            map.addControl(new YMaps.Zoom());
            map.addControl(new YMaps.ToolBar());
            if (YMaps.location) {
                var center = new YMaps.GeoPoint(YMaps.location.longitude, YMaps.location.latitude);
                map.setCenter(center, 10);
            } else {
                map.setCenter(new YMaps.GeoPoint(37.64, 55.76), 10);
            }
            var address = $("#" + id + "_address").html();
            var geocoder = new YMaps.Geocoder(address);
            //
					
            YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
                if (this.length()) {
                    //alert("Найдено :" + this.length());
                    //map.addOverlay(this.get(0));
							
                    map.panTo(this.get(0).getGeoPoint())
                    map.setZoom(15, {
                        smooth: true, 
                        position: this.get(0).getGeoPoint(), 
                        centering: true
                    });
                    map.addOverlay(geocoder);
                }else {
                    alert("Ничего не найдено")
                }
            });
        });								
    });
}


var gal_page = 0;
var total_elem = 9;

function update_gallery(id){
    var name = $('a[href*="#album_'+ id + '"]').find("em").html();
    $('a[href*="#album_'+ id + '"]').parent('li').addClass('ac');
    $("#gallery_h1").html(name);
    $('.wrap').load('/photoalbum/json_album/' + id + '/pgh_header/', function(){
        $('.rightfoto').show();
        crop_gal();
        pushDropboxUrls();
    });
}

function crop_gal(){
    $("#loading").hide();
    var elems = $(".tumbs > li");
    var el_size = elems.size();
//    var total_pages = Math.ceil(el_size / total_elem);
//    var start_elem = gal_page * total_elem;
//    var end_elem = (gal_page + 1) * total_elem;
    //alert (start_elem + " - " + end_elem + " - " + gal_page + " = " + total_pages);
    //alert (gal_page);
//    if (gal_page == 0){
        $("#page_back").parent().hide();
//        $("#page_forward").parent().show();
		$("#page_forward").parent().hide();
//    }
//   if (gal_page == total_pages - 1){
//        $("#page_forward").parent().hide();
//        $("#page_back").parent().show();
//   }
//    for (var i=0; i<el_size; i++){
//        if (i >=end_elem || i < start_elem){
//           $(elems[i]).hide();
//        }
//        else {
//            $(elems[i]).show();
//        }
//    }
	for (var i=0; i<el_size; i++){
		$(elems[i]).show();
	}
}

function chper(id){
    //alert (id);
    $("#personholder").html("<img src=\"/images/2load.gif\" style=\"margin: 10px;\" />");
    $("#personholder").load("/catalog/getObjectsListAjax/" + id + "/kado_top/", function(){
        $(".otp").click(function(){
            var pos = $(this).offset();
            var id = $(this).attr('id');
            var curof = $("#form_" + id).offset();
            $("#form_" + id).offset({
                top:pos.top-20, 
                left: curof.left
            });
            
        })
    });
    $(".cr").find('li.ac').removeClass('ac');
    $("#pli_"+id).addClass('ac');
    
    
}

function sendpersonal(id){
    var txt = $("#"+id).find('textarea').val(); 
    if (!txt){
        alert('Нужно написать сообщение');
    }
    else {
        var data = $("#"+id).serialize();
        var okid = $("#"+id).attr('s');
        var url = "/webforms/ajax_send/" + okid + "/";
        $.post(url, data, function(response){
            if (response=="0"){
                alert('Ошибка. Ваше сообщение не было отправлено.');
            }
            else {
                alert('Сообщение отправлено. Спасибо!');
            }
            $("#"+id).get(0).reset()
            $("#form_a_"+okid).hide();
        });
    }
}

function update_otdel(id){
    $("#personholder").html('');
    $(".cr").html("<img src=\"/images/2load.gif\" style=\"margin: 10px;\" />");
    $(".cr").load("/catalog/getCategoryListAjax/" + id + "/kado_top/", function(){
        var id = $(".cr a:first").attr('s');
        chper(id);
    });
    $(".conmenu").find(".ac").removeClass('ac');
    $("#li_"+id).addClass('ac');
            
           
}


function chpersonal_man(){
    $("#personholder").html('');
    $('.conmenu').find('.ac').removeClass('ac');
    $('.cr').html("<ul><li id=\"pp\" class=\"ac\"><a onclick=\"return false;\" title=\"Отдел продаж\" id=\"pp1\" href=\"#personal\" style=\"cursor: default;\"><span>Персональные менеджеры</span><em></em></a></li></ul>");
    $("#personholder").load("/catalog/getPersonalManagers/kado_top/", function(){
        $(".otp").click(function(){
            var pos = $(this).offset();
            var id = $(this).attr('id');
            var curof = $("#form_" + id).offset();
            $("#form_" + id).offset({
                top:pos.top-20, 
                left: curof.left
            });
            
        })
    });      
}

 var dropboxQ = [];
var dropBoxQSended = 0;
// Получить размер файла для дропбокса..
function pushDropboxUrls() {
    var elements = $(".rar3");
    for(var i = 0; i < elements.length; i++) {
        var em =  $(elements[i]).find("em");
        if($(em).text() == "") {
            var link = $(elements[i]).find("a").attr("href");
            link = link.substr(link.indexOf('http://') + 7);
            dropboxQ.push({
                            url : link,
                            wrap : em
                            });
        }
    }

    var interval = setInterval(function() {
        // Если запрос не послан, то посылаем..
        if(dropBoxQSended < 2) {
            if(dropboxQ.length > 0) {
                var element = dropboxQ[0];
                dropboxQ.shift();
                $.ajax({
                    url : "http://" + location.host + "/photoalbum/get_dropbox_filesize?url=" + element.url + "&t=" + (new Date().getTime()),
                    success : function(data, status, xhr) {
                        // Может, надо будет повторить потом запрос..
                        if(data != '?') {
                            $(element.wrap).html(data + " МБ");
                            dropBoxQSended--;
                        } else {
                            dropboxQ.push(element); // Потом как-нибудь попробуем запросить..
                        }
                    }
                });
                dropBoxQSended++;
            }
        }

        if(dropboxQ.length == 0) {
            clearInterval(interval);
        }

    }, 1000);
}


function chb_bukva(href){
    //var elem = $(this).attr('href');
    $("#et").hide();
    $(href).show();
    open_inst = href;
    $("#fs_zag").hide();
    $("#desc").html("");
    $("#ffiles").html("");
    
    $(document).ready(function(){
        var brid = $(".podmenu li:first").find("a").attr('s');
        var part = $(".podmenu li:first").find("a").attr('rel');
        $(".podmenu li:first").addClass('ac');		
        $("#desc").html("<img src=\"/images/load.gif\" alt=\"Загрузка...\" style=\"margin: 0 auto; display:block; \" />");
        $.getJSON('jsondata/getBrandDescr/' + brid + '/' + part + '/', function(data){
            //            //alert(data['descr']);
            $("#desc").html(data['descr']);
            $("#ffiles").html("<img src=\"/images/load.gif\" alt=\"Загрузка...\" style=\"margin: 0 auto; display:block; \" />");
            $("#ffiles").load("/jsondata/getFiles/" + brid + "/" + part + '/', function(){
                $("#fs_zag").show();
            });	
            $(".video").click(function(){
                //alert($(this).attr('href'));
                $.prettyPhoto.open($(this).attr('href'));
                return false;
            });
        });
    });
}


$(document).ready(function() {
    if (altname=="shourum"){
        $("#shourum").addClass('ac2');
        $("#catalog").removeClass('ac1');
        current_menu = "shourum";
    }
    if (altname=="oboi_na_sklade"){
        $("#oboi_na_sklade").addClass('ac3');
        $("#catalog").removeClass('ac1');
        current_menu = "oboi_na_sklade";
    }
    if (altname=="sotrudnichestvo"){
        $("#sotrudnichestvo").addClass('ac4');
        $("#catalog").removeClass('ac1');
        current_menu = "sotrudnichestvo";
    }
    if (altname=="instrukcii"){
        $("#instrukcii").addClass('ac5');
        $("#catalog").removeClass('ac1');
        current_menu = "instrukcii";
    }
    if (altname=="dlya_pressy"){
        $("#dlya_pressy").addClass('ac6');
        $("#catalog").removeClass('ac1');
        current_menu = "dlya_pressy";
    }
    if (altname=="tkani" || altname=="oboi" || altname=="aksessuary" || altname=="karnizy" || altname=="zhalyuzi" || altname=="kovry" || altname=="svetilniki" || altname=="podemnye_sistemy" || altname=="katalog" || altname=="category_brands" || altname=="brand"){
        //$("#dlya_pressy").addClass('ac6');
        $("#catalog").addClass('ac1');
        $("#menu2").show();
        current_menu = "catalog";
    }


    $("a[rel^='prettyPhoto']").prettyPhoto(
    {
        show_title: false,
        social_tools: false,
        markup: '<div class="pp_pic_holder"> \
						<div class="ppt">&nbsp;</div> \
						<div class="pp_top"> \
							<div class="pp_left"></div> \
							<div class="pp_middle"></div> \
							<div class="pp_right"></div> \
						</div> \
						<div class="pp_content_container"> \
							<div class="pp_left"> \
							<div class="pp_right"> \
								<div class="pp_content"> \
									<div class="pp_loaderIcon"></div> \
									<div class="pp_fade"> \
										<a class="pp_close" href="#" style="top:-20px;right:0px;">Close</a> \
                                                                                 \
										<div class="pp_hoverContainer"> \
											<a class="pp_next" href="#">next</a> \
											<a class="pp_previous" href="#">previous</a> \
										</div> \
										<div id="pp_full_res"></div> \
										<div class="pp_details"> \
											<div class="pp_nav"> \
												<a href="#" class="pp_arrow_previous">Previous</a> \
												<p class="currentTextHolder">0/0</p> \
												<a href="#" class="pp_arrow_next">Next</a> \
											</div> \
											<p class="pp_description"></p> \
											{pp_social} \
											<a href="#" class="pp_expand" title="Expand the image" style="right: 0; top:5px;">Expand</a>  \
										</div> \
									</div> \
								</div> \
							</div> \
							</div> \
						</div> \
						<div class="pp_bottom"> \
							<div class="pp_left"></div> \
							<div class="pp_middle"></div> \
							<div class="pp_right"></div> \
						</div> \
					</div> \
					<div class="pp_overlay"></div>'
			
    }
    );
	
    var br = gup('id');
    if (br){
        $("#brand_" + br).addClass('ac');
    }
	
    try {
        if (catalog_open_flag && catalog_open_flag != null && catalog_open_flag != false){
            $("#catopen").attr("state","on");
            $("#menu2").show();
        }
    }
    catch (e) {}
	
    // Выберем пункт по умолчанию, который раскрылся
    var hashs = [{hash: "msk",
                  num: 341},
                 {hash: "spb",
                  num: 342},
                  {hash: "rstv",
                  num: 343},
                  {hash: "nsb",
                  num: 344},
                  {hash: "amta",
                   num: 345}
                 ]
    var isFinded = false; // Флаг, показывающий, есть ли хэш в урле
    if(typeof(window.location.hash) != 'undefined' && window.location.hash != "" && window.location.hash != null) {
        for(var i = 0; i < hashs.length; i++) {
            if(window.location.hash == "#" + hashs[i].hash) {
                $("#" + hashs[i].num + "_a_li").addClass('ac');
                $("#" + hashs[i].num + "_a_div").show();
                isFinded = true;
                break;
            }    
        }
    }
    if(!isFinded) {
        $("#341_a_li").addClass('ac');
        $("#341_a_div").show();
    }
    map_init();
	
    $('.sh').click(function() {
        var id = $(this).attr('id');
        /*if (open_news != "" && open_news != id){
			$("#" + open_news + "_full").hide();
			$("#" + open_news + "_short").show();
		}
		*/
        $("div.topnew:hidden").show();
        $("div.blok:visible").hide();
        //$(".block").hide();
        
        $("#" + id + "_full").show("slow", function(){
//            alert("ok")
            $(this).css({"display":"block"});
        });

        $("#" + id + "_short").hide();
        open_news = id;
        elementClick = $(this).attr("href");
        destination = $(elementClick).offset().top;
        if($.browser.safari){
            $('body').animate( {
                scrollTop: destination
            }, 1100 );
        }else{
            $('html').animate( {
                scrollTop: destination
            }, 1100 );
        }
        return false;
    });
	
    $(".dropout").click(function(){
        var id = $(this).attr('id');
        $("#" + id + "_full").hide();
        $("#" + id + "_short").show();
        return false;	
    });
	
    $(".upd").click(
        function(){
            var id = $(this).attr('s');
            var tx = $(this).find('em').html();
            //alert(tx);
            $("#whichcity").html(tx);
            $("#" + curcity + "_a_div").hide();
            $("#" + id + "_a_div").show();
            $("#" + curcity + "_a_li").removeClass();
            $("#" + id + "_a_li").addClass('ac');
            curcity = id;
			
            map_init();
			
            return false;
        }
        );
	
    $(".ss").click(
        function(){
            var state = $(this).attr('state');
            var id = $(this).attr('id');
            if (!state || state===null || state=="off"){
                $("#" + id + "_div").show();
                $(this).attr('state', 'on');
                $(this).addClass("vac_act");
                $(this).attr("style", "color: #535353;");
                if (open_vac != "" && open_vac != id && open_vac != 0){
                    //alert (open_vac);
					
                    $("#" + open_vac).attr('state','off');
                    $("#" + open_vac).attr('style', 'color:#B20932;');
                    $("#" + open_vac).removeClass("vac_act");
                    //var temp = new Array();
                    //temp = open_vac.split("_");
                    $("#" + open_vac + "_div").hide();
                }
				
                open_vac = id;
            }
            else {	
                $("#" + id + "_div").hide();
                $(this).attr('state', 'off');
                $(this).attr('style', 'color:#B20932;');
                $(this).removeClass("vac_act");
            }
            elementClick = $(this).attr("href");
            destination = $(elementClick).offset().top;
            if($.browser.safari){
                $('body').animate( {
                    scrollTop: destination
                }, 1100 );
            }else{
                $('html').animate( {
                    scrollTop: destination
                }, 1100 );
            }
            return false;
        }
        );
	
    /*$('#catopen').click(
		function () {
			var state = $(this).attr('state');
			if (!state || state===null || state=="off"){
				$("#menu2").show();
				$(this).attr('state', 'on');
			}
			else {	
				$("#menu2").hide();
				$(this).attr('state', 'off');
			}
			return false;
		}
	);*/
	
    $(".back").click(function(){
        //history.back();
        //alert (refer);
        var refval = $("#referer").find('span').html();
        if (refval){
            window.location.href = refval;
        }
        else {
            history.back();
        }
        return false;
    });
	
    $(".studio").mouseover(
        function(){
            $(this).attr("style","cursor:pointer;");
        }
        );
	
    $(".studio").click(function(){
        window.open("http://ready2go.ru/?utm_source=Kado&utm_medium=r2g_logo&utm_campaign=footer_link");
        return false;
    });
	
    var err = gup("_err");
    if (err){
        $("#error_dialog").dialog({
            modal:true,
            buttons: {
                Ok: function(){
                    $(this).dialog("close");
                }
            }
        });
    }
	
    if (open_inst != 0 && open_inst != "" && open_inst != null){
        $('#et').hide();
    }
	
    $(".chb").click( function(){
        $('#et').hide();
        if (open_inst != 0 && open_inst != "" && open_inst != null){
            $(open_inst).hide();
            //alert (open_inst);
            var opname = "a[href|='" + open_inst + "']";
            $(opname).parent().removeClass('ac');
            // Фикс
            $(open_inst).find("li.ac").removeClass('ac');
        }
        var elem = $(this).attr('href');
        $(elem).show();
        open_inst = elem;
        $(this).parent().addClass('ac');
        $("#fs_zag").hide();
        $("#desc").html("");
        $("#ffiles").html("");
        return false;
    });
	
    var current_sel_br = ""; 
	
    $(".sel_br").click( function(){
        var id = $(this).attr('s');
        var part = $(this).attr('rel');
        $("div.bl_b_l").find('.ac').removeClass('ac');
        $(this).parent().addClass('ac');		
        $("#desc").html("<img src=\"/images/load.gif\" alt=\"Загрузка...\" style=\"margin: 0 auto; display:block; \" />");
        $.getJSON('jsondata/getBrandDescr/' + id + '/'+ part + '/', function(data){
            //alert(data['descr']);
            $("#desc").html(data['descr']);
            $("#ffiles").html("<img src=\"/images/load.gif\" alt=\"Загрузка...\" style=\"margin: 0 auto; display:block; \" />");
            $("#ffiles").load("/jsondata/getFiles/" + id + "/"+ part + '/', function(){
                $("#fs_zag").show();
            });	
            $(".video").click(function(){
                //alert($(this).attr('href'));
                $.prettyPhoto.open($(this).attr('href'));
                return false;
            });
        });
		
		
    });

    $(".chalbum").click(function(){
        var id = $(this).attr('s');
        $(".chalbum").parent().removeClass('ac');
        $(this).parent().addClass('ac');
        $("#loading").show();
        $('.rightfoto').show();
        gal_page = 0;
        update_gallery(id);
		
    });
	
    $("#page_forward").click(function(){
        $("#loading").show();
        gal_page = gal_page + 1;
        var t = setTimeout(crop_gal, 500);
        //crop_gal();
        return false;
    });
    $("#page_back").click(function(){
        $("#loading").show();
        gal_page = gal_page - 1;
        var t = setTimeout(crop_gal, 500);
        return false;
    });
	
    $(".dispathe_form").bind('submit', function(){
        var valid="false";
        try {
            valid = $(this).validationEngine('validate');
        }
        catch (e) {}
        if (valid=="false" || valid == false){
            $("#dialog_text").html('Введите правильный e-mail.');
            $("#error_dialog").dialog({
                modal:true,
                buttons: {
                    Ok: function(){
                        $(this).dialog("close");
                    }
                }
            });
        }
        else {
            $("#imgload").show();
            $("#sendbutton").hide();
            var formdata = $(this).serialize();
            $.post("/dispatches/subscribe_json/", formdata, function(data){
                $("#info_text").html(data);
                $("#imgload").hide();
                $("#sendbutton").show();
                $("#info_dialog").dialog({
                    modal:true,
                    buttons: {
                        Ok: function(){
                            $(this).dialog("close");
                        }
                    }
                });
            });
        }
        return false;
    });

    $(".lke_close").click(function(){
        $("#lkenter").hide();
        return false;
    });
	
    $(".lke_open").click(function(){
        $("#lkenter").show();
        return false;
    });
	
    $(".lke_close").bind('mouseover', function(){
        $(this).css('cursor','pointer');
        return false;
    });
    $(".lke_open").bind('mouseover', function(){
        $(this).css('cursor','pointer');
        return false;
    });
	
    $(".chcity").click(function(){
        var id = $(this).attr('s');
        update_otdel(id);
    });
        
    $('.yman').click(function(){
        chpersonal_man();
    });


});
