var h_filename = 'hour_clock.png';
var m_filename = 'minute_clock.png';
function setWorldTime(date){
        var m_time = new Date(date);
        var v_time = new Date(date);
        var sh_time = new Date(date);
        var s_time = new Date(date);
        var minutes = m_time.getMinutes();
        var m_hours = m_time.getHours();
        var v_hours = v_time.getHours();
        var sh_hours = sh_time.getHours();
        var s_hours = s_time.getHours();

        v_time.setHours(v_time.getHours()+7);
        v_hours = v_time.getHours();
        sh_time.setHours(sh_time.getHours()+4);
        sh_hours = sh_time.getHours();
        s_time.setHours(s_time.getHours()+5);
        s_hours = s_time.getHours();

        if(minutes!=0){
                var m_hours_offset = (m_hours!=0||m_hours!=12)?((m_hours>12)?(((m_hours-12)*2+1)*86):((m_hours*2+1)*86)):86;
                var v_hours_offset = (v_hours!=0||m_hours!=12)?((v_hours>12)?(((v_hours-12)*2+1)*86):((v_hours*2+1)*86)):86;
                var sh_hours_offset = (sh_hours!=0||m_hours!=12)?((sh_hours>12)?(((sh_hours-12)*2+1)*86):((sh_hours*2+1)*86)):86;
                var s_hours_offset = (s_hours!=0||m_hours!=12)?((s_hours>12)?(((s_hours-12)*2+1)*86):((s_hours*2+1)*86)):86;
        }
        else{
                var m_hours_offset = (m_hours!=0||m_hours!=12)?((m_hours>12)?((m_hours-12)*2*86):(m_hours*2*86)):0;
                var v_hours_offset = (v_hours!=0||m_hours!=12)?((v_hours>12)?((v_hours-12)*2*86):(v_hours*2*86)):0;
                var sh_hours_offset = (sh_hours!=0||m_hours!=12)?((sh_hours>12)?((sh_hours-12)*2*86):(sh_hours*2*86)):0;
                var s_hours_offset = (s_hours!=0||m_hours!=12)?((s_hours>12)?((s_hours-12)*2*86):(s_hours*2*86)):0;
        }
        var minutes_offset = minutes*86;
        if($.browser.msie && $.browser.version == '6.0'){
                h_filename = 'hour_clock_ie.gif'
                m_filename = 'minute_clock_ie.gif'
        }
        $('#moscow_time .hours').css('background', 'url(/templates/site/images/'+h_filename+') left -'+m_hours_offset+'px');
        $('#shanghai_time .hours').css('background', 'url(/templates/site/images/'+h_filename+') left -'+sh_hours_offset+'px');
        $('#seul_time .hours').css('background', 'url(/templates/site/images/'+h_filename+') left -'+s_hours_offset+'px');
        $('#vanino_time .hours').css('background', 'url(/templates/site/images/'+h_filename+') left -'+v_hours_offset+'px');

        $('#moscow_time .minutes').css('background', 'url(/templates/site/images/'+m_filename+') left -'+minutes_offset+'px');
        $('#shanghai_time .minutes').css('background', 'url(/templates/site/images/'+m_filename+') left -'+minutes_offset+'px');
        $('#seul_time .minutes').css('background', 'url(/templates/site/images/'+m_filename+') left -'+minutes_offset+'px');
        $('#vanino_time .minutes').css('background', 'url(/templates/site/images/'+m_filename+') left -'+minutes_offset+'px');

        minutes = (minutes<10)?('0'+minutes):minutes;
        m_hours = (m_hours<10)?('0'+m_hours):m_hours;
        v_hours = (v_hours<10)?('0'+v_hours):v_hours;
        sh_hours = (sh_hours<10)?('0'+sh_hours):sh_hours;
        s_hours = (s_hours<10)?('0'+s_hours):s_hours;
        $('#moscow_time span').html(m_hours+' : '+minutes);
        $('#shanghai_time span').html(sh_hours+' : '+minutes);
        $('#seul_time span').html(s_hours+' : '+minutes);
        $('#vanino_time span').html(v_hours+' : '+minutes);

        setTimeout(setWorldTime,60000);
}


$(document).ready(function(){
    setWorldTime(cur_date);
	$('#ch a').live('click',function(){
		if(lang==1)
			$.facebox('<p style="margin: 20px; font-size: 16px;">В настоящий момент китайская версия сайта недоступна.</p>');
		else
			$.facebox('<p style="margin: 20px; font-size: 16px;">Currently, the Chinese version of the site is unavailable.</p>');		
		return false;
	});
	
	$('#kor a').live('click',function(){
		if(lang==1)
			$.facebox('<p style="margin: 20px; font-size: 16px;">В настоящий момент корейская версия сайта недоступна.</p>');
		else
			$.facebox('<p style="margin: 20px; font-size: 16px;">Currently, the Korean version of the site is unavailable.</p>');		
		return false;
	});
	
    $('#body_navlist').data('offset', 0);
    $('.hm1').data('show', 0);
    
    $(".filial").live('mouseover',function(){
        $(this).css('width','auto').css('z-index','10000');
    });
    $(".filial").live('mouseout',function(){
        $(this).css('width','12px').css('z-index','1000');
    });

    $('#menu > li a').live('click',function(){
        if(($('li',$(this).parent()).length>0)){
            if($('.dropdown',$(this).parent()).is(':hidden'))
                    $('.dropdown',$(this).parent()).slideDown('1000');
            else
                    $('.dropdown',$(this).parent()).slideUp('1000');
            return false;
        }
    });
    $('#more').live('click',function(){
        $(this).remove();
        $('#fulltext').slideDown('1000');
        if(lang == 1)
            $('#fulltext').after('<a id="slide_up" href="#">Свернуть</a>');
        else
            $('#fulltext').after('<a id="slide_up" href="#">Slide up</a>');
        return false;
    });

    $('#slide_up').live('click', function(){
        $(this).remove();
        $('#fulltext').slideUp('1000');
        if(lang == 1)
            $('#fulltext').before('<a id="more" href="#">Развернуть далее</a>');
        else
            $('fulltext').before('<a id="more" href="#">Expand further</a>');
        return false;
    })

    $("#login_link").live('click',function(){
        $('#geopos').hide();
        $('#login_div').slideDown('1000');
        return false;
    });

    $('#login').live('focus',function(){
        if($(this).val()=='Логин' || $(this).val()=='Login')
        {
            $(this).val('');
            $(this).css('color', '#455155');
        }
    });

    $('#pass').live('focus',function(){
        if($(this).val()=='Пароль' || $(this).val()=='Password')
        {
            $(this).remove();
            $('#login').after('<p><input id="pass" type="password" value="" /></p>');
            $('#pass').css('color', '#455155').focusin();
        }
    });
    $("#login").live('blur',function () {
        if ($(this).val()=='')
        {
           if(lang == 1)
                $(this).val('Логин');
           else{
               $(this).val('Login');
           }
           $(this).css('color', '#d4d4d5');
        }
    });
    $("#pass").live('blur',function () {
        if ($(this).val()=='')
        {
            $(this).remove();
            $('#login').after('<p><input id="pass" type="text" value="" /></p>');
            if(lang == 1)
                $('#pass').val('Пароль');
            else{
                $('#pass').val('Password');
            }
            $('#pass').css('color', '#d4d4d5');
        }
    });
    $('#close a').live('click',function(){
        $("#login_div").hide();
        $("#geopos").fadeIn('1000');
        if($.browser.msie && $.browser.version == '6.0')
        var t = setTimeout(function(){$('#geopos').css({'background':'none','filter':'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="/templates/site/images/geopos_back.jpg", sizingMethod="crop")'});},'500');
        return false;
    });
    $('#login_btn').live('submit',function(){
        $(this).click();
        return false;
    });
    $('#login_btn').live('click',function(){
       if ($('#login').val()=='' || $('#login').val()=='Логин')
       {
           $.facebox('<p style="margin: 20px; font-size: 16px;">Введите логин!</p>');
       }
       else if ($('#pass').val()=='' || $('#pass').val()=='Пароль')
       {
           $.facebox('<p style="margin: 20px; font-size: 16px;">Введите пароль!</p>');
       }

       else
       {
           $.post("http://km.creatonica.ru/core/modules/loginSite.php", {
                login: $('#login').val(),
                pass:  $('#pass').val(),
                type: '0'
           }, function(data)
              {     //alert(data.g)
                  if (data.s == 'ok')
                  {
                      if($("input:checked").length == 1)
                      {   //alert('s');
                          save = data.r;
                          setCookie("saveLogin", null,  1, "/");
                          setCookie("savelogin", save,  1, "/");
                      }
                      else
                      {
                          save = 'anonim';
                          setCookie("saveLogin", null,  1, "/");
                          setCookie("savelogin", save,  1, "/");
                      }
                      window.location ="http://km.creatonica.ru/personal_page";
                  }
                  else
                     $.facebox('<p style="margin: 20px; font-size: 16px;">Неверный логин или пароль</p>');
              },'json');
       }
                   return false;
    });
    $('#geopos').live('click',function(){
       $.post("http://km.creatonica.ru/core/modules/loginSite.php", {
            type: '1'
       }, function(data){
             if (data.ids != 'anonim' && data.ids != 'null')
             {
                 window.location ="http://km.creatonica.ru/personal_page";
                 save = data.ids;
                 setCookie("saveLogin", null,  1, "/");
                 setCookie("savelogin", save,  1, "/");
             }
             else
             {
                $("#login_link").click();
             }
          },'json');

        return false;
    });
    $('#changeLogin').click(function(){
               $.post("/history_gruz/getlogin/",
                    function(data){
                         $.facebox('<div id="changeloginWindow"><div id="changeForm"><p><h2>Введите новые данные</h2></p><p>Логин</p><input type="text" id="newLogin" value="'+data.login+'"><p>Ваше имя</p><input type="text" id="newName"><p>E-mail</p><input type="text" id="email"><p>Пароль</p><input id="newPass" type="password"><p>Повторите пароль</p><input id="newPassCopy" type="password"><p id="errorPass" style="display: none">Пароли не совпадают</p><p><input type=submit id="saveChange" value="Сохранить"></p><p id="errorMsg">Заполните все поля или закройте окно для отмены изменения данных</p></div></div>');
                         $('#saveChange').click(function(){
                                if($('#newLogin').val() == '' || $('#newPass').val() == '') 
                                {
                                    $('#errorMsg').show();
                                }
                                else if ($('#newPass').val() != '' && $('#newPass').val() != $('#newPassCopy').val())
                                {
                                     $('#errorPass').show();
                                     $('#errorPass').fadeOut(2500);
                                }
                                else
                                {
                                    $.post("/history_gruz/modifylogin/",
                                    {
                                        login: $('#newLogin').val(),
                                        pass: $('#newPass').val(),
                                        nickname: $('#newName').val(),
                                        email: $('#email').val()
                                    },function(data)
                                    {
                                        if (data.status == 'ok')
                                        {
                                            
                                            //$('#changeForm').slideUp('slow');
                                            $('#changeloginWindow').html('<h2 id="okChange" style="margin-left: -15%">Данные успешно изменены</h2>');
                                            
                                            //$('#okChange').show('slow');
                                            
                                        }
                                        if (data.status == 'duplicate')
                                        {
                                             $('#changeloginWindow').html('<h2 id="okChange" style="margin-left: -15%">Пользователь с таким именем уже зарегистрирован!</h2>');
                                        }
                                    },'json');    
                                }
                             });
                     },'json')  
             });
    $('#nav_left').css('cursor','pointer').mouseover(function(){
                 
                 $(this).attr('src','/templates/site/images/left_down_act.png');
             }).mouseout(function(){
                 $(this).attr('src','/templates/site/images/left_down_n_act.png'); 
             });
             $('#nav_right').css('cursor','pointer').mouseover(function(){
                 
                 $(this).attr('src','/templates/site/images/right_down_act.png');
             }).mouseout(function(){
                 $(this).attr('src','/templates/site/images/right_down_n_act.png'); 
             });    
             
             $('#nav_right').click(function() {
                 if ($('#body_navlist').data('offset')<maxOffset)
                 { 
                        $('#body_navlist').data('offset', $('#body_navlist').data('offset') + 1);
                        $('#body_navlist').animate({
                          'marginLeft': '-=168px'
                          }, 500);
                 }                          
                  return false;
             });
             $('#nav_left').click(function() {
                if ($('#body_navlist').data('offset')>0)
                {
                    $('#body_navlist').data('offset', $('#body_navlist').data('offset') - 1);
                    $('#body_navlist').animate({
                           'marginLeft': '+=168px'
                           }, 500);
                }                           
                    return false;
             });
    $('#mygruz').click(function(){
            window.location ="http://km.creatonica.ru/personal_page"; 
             
         });
     $('.pm1').toggle(                
             function () {
                    ind = $(this).attr('id');
                    ind = parseInt(ind.charAt(2));
                    $(this).find('.borBottom').css('color','#0d6eb1');
                    $(this).css ('background-image', 'url(/templates/site/images/clip_b.png)');
                    $(this).find('.borBottom').text(''+langType[userLang].v+'');

                    gmarkers[ind].hide();
                    gmarkers[ind].closeInfoWindow();
               },
               function () {
                    ind = $(this).attr('id');
                    ind = parseInt(ind.charAt(2));
                    $(this).find('.borBottom').css('color','#ff2d2d');
                    $(this).css ('background-image', 'url(/templates/site/images/clip_r.png)');
                    $(this).find('.borBottom').text(''+langType[userLang].nv+'');
               
                    gmarkers[ind].show();
                }
    );  

       $('.n1').css('cursor','pointer').click(function(){
               ind = $(this).attr('id');
               ind = parseInt(ind.charAt(1));
               if (!gmarkers[ind].isHidden())
               {
                    gmarkers[ind].openInfoWindowHtml(gmarkers[ind].content);
                    map.setCenter(gmarkers[ind].getLatLng(), 10); 
               }
           
       });
       $('#logout').click(function(){
            $.post("/personal_page/userout/",
              function(data)
              {
                  if (data.status == 'ok'){
                    window.location ="http://km.creatonica.ru/";
                  }
              },'json');  
           return false;   
         });

         $('#historygruz').click(function(){
              window.location ="http://km.creatonica.ru/history_gruz";  
           return false;   
         });
        $('.hm1 a').live('click',function(){
            
            return false;
         });
         $('.hm1').click(
                function()
                {   
                     if ($(this).data('show')==1){
                         $('.borBottom').css('color','#0d6eb1');
                         $('.borBottom').text(''+langType[userLang].v+'');
                         $('.hm1').css('background-image', 'url(/templates/site/images/clip_b.png)'); 
                         $('#tabhistory').slideUp();
                          $(this).data('show', 0);
                         }
                     else{
                         $('.hm1').data('show', 0); 
                         $(this).data('show', 1);
                         
                         $('.borBottom').css('color','#0d6eb1');
                         $('.borBottom').text(''+langType[userLang].v+'');
                         $('.hm1').css('background-image', 'url(/templates/site/images/clip_b.png)'); 
                         $('#tabhistory').slideUp();
                         
                         ind = $(this).attr('id');
                         
                         ind = parseInt(ind.charAt(2));
                         $(this).find('.borBottom').css('color','#ff2d2d');
                         $(this).css('background-image', 'url(/templates/site/images/clip_r.png)');
                         $(this).find('.borBottom').text(''+langType[userLang].nv+'');
                         gmapdata.splice(0,gmapdata.length);
                        // if($('#tabhistory').data('idG') != $(this).attr('id'))
                         
                             
                            //$('#tabhistory').data('idG', $(this).attr('id')); 
                            $.post("/history_gruz/gethistorydata/",{id: $(this).attr('id')},
                            function(data)
                            {
                                          
                                $('#tabhistory').html('<tr><td>'+langType[userLang].p+'</td><td>'+langType[userLang].d+'</td><td>'+langType[userLang].lt+'</td><td>'+langType[userLang].ln+'</td><td>'+langType[userLang].ds+'</td><td>'+langType[userLang].swn+'</td></tr>'+data.historydata);
                                    //alert(data.hInd);
                                    for (i=1;i<=data.hInd;i++)
                                    {
                                        //{name:"'.$key->name.'", lat:"'.$key->g_width.'", lng:"'.$key->g_height.'", type:"'.$key->type.'", num:"'.$key->id_second.'", date:"'.$key->date.'", place:"'.$key->place.'", descr:"'.$key->description.'"},'; 
                                        //gmarkers[i-1]='';
                                        t = $('#gt'+i+'').attr('name');
                                        t = t.charAt(2);
                                        gmapdata[i-1] = {name:""+$('#'+data.id+'').text()+"", lat:""+$('#wt'+i+'').text()+"", lng:""+$('#ht'+i+'').text()+"", type:""+t+"", date:""+$('#dt'+i+'').text()+"", place:""+$('#pt'+i+'').text()+"",descr:""+$('#des'+i+'').text()+""};
                                    }
                                   // alert(gmapdata[0].name); 
                                    initialize();
                                    
                                    $('#tabhistory :checkbox').click(function(){
                                        ind = $(this).attr('id');
                                        ind = parseInt(ind.charAt(2))-1;
                                        if($(this).attr('checked'))
                                        {
                                             gmarkers[ind].show();
                                        }
                                        else
                                        {   gmarkers[ind].hide();
                                           // gmarkers[ind].closeInfoWindow();
                                            
                                        }
                                    });
                                    $('#tabhistory').slideDown('500');
                                    
                            },'json');
                        
                         }
                     });
});
 function setCookie(name, value, expiredays, path, domain, secure)
 {
   if (expiredays) {
      var exdate=new Date();
      exdate.setDate(exdate.getDate()+expiredays);
      var expires = exdate.toGMTString();
   }
   document.cookie = name + "=" + escape(value) +
   ((expiredays) ? "; expires=" + expires : "") +
   ((path) ? "; path=" + path : "") +
   ((domain) ? "; domain=" + domain : "") +
   ((secure) ? "; secure" : "");
}  

/////////////////google Map///////////////////////
        
        
        
        function addIcon(icon) { // Add icon properties

            icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
            icon.iconSize = new GSize(38, 36);
            icon.shadowSize = new GSize(27, 24);
            icon.iconAnchor = new GPoint(15, 34);
            icon.infoWindowAnchor = new GPoint(19, 2);
            icon.infoShadowAnchor = new GPoint(18, 25);
        }
        function initialize()
        {
             //alert(gmapdata);
            /*var gmapdata = [
                        {name:"екн", lat:"54", lng:"87", type:"0", num:"кен"},
                        {name:"кен", lat:"5", lng:"5", type:"1", num:"кен"},
                        {name:"апа", lat:"45", lng:"65", type:"2", num:"апр"},
                        {name:"rty", lat:"56", lng:"75", type:"3", num:"fghu"}
                       ];*/
        if (gmapdata!='')
        {
           // alert(gmapdata[0].lat);
            var maxLat = parseFloat(gmapdata[0].lat);
            var minLat = parseFloat(gmapdata[0].lat);
            
            var  maxLng = parseFloat(gmapdata[0].lng);
            var  minLng = parseFloat(gmapdata[0].lng);
            
            for(var i = 0; i < gmapdata.length; i++) 
            {
                    if (parseFloat(gmapdata[i].lng) > maxLng )
                    {
                        maxLng= parseFloat(gmapdata[i].lng);
                    }
                    if (parseFloat(gmapdata[i].lng) < minLng )
                    {
                        minLng= parseFloat(gmapdata[i].lng);
                    }
 
                    if (parseFloat(gmapdata[i].lat) > maxLat )
                    {
                        maxLat= parseFloat(gmapdata[i].lat);
                    }
                    if (parseFloat(gmapdata[i].lat) < minLat )
                    {
                        minLat= parseFloat(gmapdata[i].lat);
                    }
            } 
            zoom=0; 
            if ( (maxLat-minLat) > (maxLng-minLng))
            {
                max =  maxLat;
                min =  minLat;
            } 
            else
            {
                max =  maxLng;
                min =  minLng;
            }
            //alert (max+','+min);
            if ( (max-min)>=3 ) zoom = 3;
            if ( (max-min)>=27 ) zoom = 2;
            //if ( (max-min)>=49 ) zoom = 2;
            if ( (max-min)>=90 ) zoom = 1;
            if ( (max-min)>=145 ) zoom = 0;
            if ( (max-min)<3 )  zoom = 5;
            if ((max-min)<2) zoom = 6;
            if ((max-min)<1) zoom = 8;
            //alert(max-min); 
            cenX =  (maxLat-minLat)/2+minLat;
            cenY =   (maxLng-minLng)/2+minLng;
            //alert(maxLat+','+minLat);
        }
        else
        {
            cenX = 50;
            cenY = 50;
            zoom = 1;
        }    
         
            map = new GMap2(document.getElementById("map_canvas"));
            map.setCenter(new GLatLng(cenX, cenY), zoom);
            map.setUIToDefault(); 
            createMarkers();
                        
        }
        
        function createMarkers()
        {       
                  var icon = new GIcon();
                 // alert(gmarkers.length);
                        for (i=0;i<gmarkers.length;i++)
                        {    //alert(i);
                             gmarkers[i].hide();
                             //gmarkers[ind].closeInfoWindow();
                        }
                        gmarkers.splice(0,gmarkers.length);
                        //alert(gmarkers.length);
                  if (gmapdata!=0)
            for(var i = 0; i < gmapdata.length; i++) {
                
                          
                          
                          switch (gmapdata[i].type)
                          {
                            case '0':
                            {  
                                icon.image = "/templates/site/images/pointImgGruz.png";
                                break;
                            }
                             case '1':
                             {  
                                icon.image = "/templates/site/images/trainImgGruz.png";
                                break;
                             }
                             case '2':
                             {  
                                icon.image = "/templates/site/images/autoImgGruz.png";
                                break;
                             }
                             case '3':
                             {  
                                icon.image = "/templates/site/images/seaImgGruz.png";
                                break;
                             }
                          }
                          addIcon(icon);
                          points[i] = new GLatLng(parseFloat(gmapdata[i].lat), parseFloat(gmapdata[i].lng));
                          gmarkers[i] = new GMarker(points[i], icon);
                          var html ="<div class='infowindow'>" +
                          "<img src= "+icon.image+" style='float: left;'><br /><strong>"+ gmapdata[i].name + "<\/strong><br /><br /><p>"+langType[userLang].p+": "
                          +gmapdata[i].place+"<\/p><p>"+langType[userLang].lt+": " +
                          gmapdata[i].lat + "<\/p><p>"+langType[userLang].ln+": "
                          +gmapdata[i].lng+"<\/p><p>"+langType[userLang].ds+": "+
                          gmapdata[i].descr+"<\/p><p>"+langType[userLang].d+": "+
                          gmapdata[i].date+"<\/p><\/div>";
                          gmarkers[i].content = html;
                          gmarkers[i].nr = i;
                          addClickevent(gmarkers[i]);
                          map.addOverlay(gmarkers[i]);
            }
            
        }
        function addClickevent(marker) 
        {                 
            GEvent.addListener(marker, "click", function() {
                marker.openInfoWindowHtml(marker.content);
                map.setCenter(marker.getLatLng(),6);
            });
                            
            
            GEvent.addListener(marker, "infowindowclose", function()
            {      
                   map.setCenter(new GLatLng(cenX, cenY), zoom);
            });
            return marker;
        }   

        ////////////////////////google Map End///////////////////////         



