var curr_text  = '';
var current_id = -1;
var timer;
var isTimerOn = false;
//var active = false;
var last_menu_item_id;
var current_open_id = false;
var item_in_stack;


function BrowseServer()
{
    // You can use the "CKFinder" class to render CKFinder in a page:
    var finder = new CKFinder() ;
    finder.BasePath = '/ckfinder/' ;    // The path for the installation of CKFinder (default = "/ckfinder/").
    finder.SelectFunction = SetFileField ;
    finder.Popup() ;
 
    // It can also be done in a single line, calling the "static"
    // Popup( basePath, width, height, selectFunction ) function:
    // CKFinder.Popup( '../../', null, null, SetFileField ) ;
    //
    // The "Popup" function can also accept an object as the only argument.
    // CKFinder.Popup( { BasePath : '../../', SelectFunction : SetFileField } ) ;
}
 
// This is a sample function which is called when a file is selected in CKFinder.
function SetFileField( fileUrl )
{
    
    $('#link_'+current_id).attr('value',fileUrl);
    $('#form_'+current_id).submit();
}


function checkLast()
{
    //active=false;
    //alert('asd');
    current_open_id = false;
    //$('#subj').attr('value',last_menu_item_id);
  //  $('.content').prepend('Inside checklast last_menu_item_id='+last_menu_item_id+'<br />');
    if(last_menu_item_id)
    {
     //   $('.content').prepend('Inside checklast trigger last_menu_item_id='+last_menu_item_id+'<br />');
        $('#menu_item_'+last_menu_item_id).trigger('mouseenter');    
    }
    
}

function hideSubmenuItems()
{
       //$('.submenu').stop(false,true); 
       $('.submenu').hide(500);
       
       setTimeout('checkLast()',500);
}

function hideSubmenuItemsFast()
{  
  //  $('.submenu').stop(false,true);
  //  $('.submenu').hide();    
}




var fleet_pct = 0;

$(document).ready(function(){   
    
    
    //alert($('body').width());
    //$('div.flash').width($('body').width()+Math.ceil((1600-$('body').width())/2));
    
    
    $('li.inner_click').click(function(){
        window.location.href = $(this).children('a.inner_link').attr('href');
    });
    
    $('#fleet_btn_right').click(function(event){
        
        
        
        if($('div#fleet_'+(fleet_pct+3)).length)
        {
            $('div.gal').hide();
            $('div#fleet_'+(fleet_pct+1)).show();
            $('div#fleet_'+(fleet_pct+2)).show();
            $('div#fleet_'+(fleet_pct+3)).show();
            fleet_pct++;
        }
        
        event.preventDefault();
    });
    
    
    $('#fleet_btn_left').click(function(event){
        
        
        
        if($('div#fleet_'+(fleet_pct-1)).length)
        {
            $('div.gal').hide();
            $('div#fleet_'+(fleet_pct-1)).show();
            $('div#fleet_'+(fleet_pct)).show();
            $('div#fleet_'+(fleet_pct+1)).show();
            fleet_pct--;
        }
        
        event.preventDefault();
    });
    
    if($("a.lightbox").length)
    {
        $("a.lightbox").lightBox();    
    }
    
    
    
    
    $("#galleryIns").find("a.gal").append("<span class=bord></span>");
    
      $('.CS_select').each(function(){
        //alert('#'+$(this).attr('id'));
        $('#'+$(this).attr('id')).customSelect();
        //$("#phone_code").customSelect();
    });
    
    $(".select_file_link").click(function(event){
        
       current_id =$(this).attr('rel'); 
       BrowseServer();     
        
        event.preventDefault();
    });
    
    
    
    if($('.middle_block').height()>$('.right_block').height())
    {
        $('.right_block').height($('.middle_block').height());
    }
    
    
    
    
    
    $(".menu_item").click(function(event){
        //alert(active);
        
        var id= $(this).attr('id').substr(10); 
        var active= false;
        last_menu_item_id = id;
        
        

        {
         last_menu_item_id  = false;   
         current_open_id = id;
       
     // alert($(this).css('background-image'));
        //$(this).css('background-image','url(/images/menu_item_hover_bg_filler.gif)');
        //$('#right_bg_'+id).attr('src','/images/menu_item_hover_bg_right.gif');
        //$('#left_bg_'+id).attr('src','/images/menu_item_hover_bg_left.gif');
      
       //hideSubmenuItemsFast();
       
       var flag = true;
       
       if($('#submenu_'+id).is(':visible'))
       {
           flag = false;
       }
       
       
       hideSubmenuItems();
       
       clearTimeout(timer);
       isTimerOn = false;
        //alert('asd');
       
       
            
       
       if($('#submenu_'+id).length)
       {
            

           if(flag)
           {
            $('#submenu_'+id).show(500);    
           }
           
           event.preventDefault();
       }
        }
   });
    
    
    
    
    
    /*
    $(".menu_item").mouseenter(function(){
        //alert(active);
        
        var id= $(this).attr('id').substr(10); 
        var active= false;
        last_menu_item_id = id;
        
        
       // $('.content').prepend('Inside mouseenete id='+id+'<br />');
        
        $("ul.submenu").each(function(){
            if($(this).is(":visible"))
            {
                active=true;
            }
        });
        
        if(active)
        {
           
            hideSubmenuItems();        
        }
        else
        {
         last_menu_item_id  = false;   
         current_open_id = id;
       
     // alert($(this).css('background-image'));
        //$(this).css('background-image','url(/images/menu_item_hover_bg_filler.gif)');
        //$('#right_bg_'+id).attr('src','/images/menu_item_hover_bg_right.gif');
        //$('#left_bg_'+id).attr('src','/images/menu_item_hover_bg_left.gif');
      
       //hideSubmenuItemsFast();
       hideSubmenuItems();
       
       clearTimeout(timer);
       isTimerOn = false;
        //alert('asd');
       
       if($('#submenu_'+id).length)
       {
       
          //var menu_el_pos = $(this).position();
           //var menu_pos = $(".menu").position();
           //alert(menu_pos.left); 
           //var submenu_pos
           //alert(menu_el_pos.left);
           
           //$('#submenu_item_'+id).hide();
           //$('#submenu_'+id).hide(); 
           //$('#submenu_item_'+id).css('top','115px');
           
           
           //alert('asd'); 
           //$('#submenu_item_'+id).css('left',(menu_pos.left+menu_el_pos.left+44+($(this).width()/2)-($('#submenu_item_'+id).width()/2)+'px'));
//           $('#submenu_'+id).css('left',(menu_el_pos.left+70+$(this).width()/2-$('#submenu_'+id).width()/2)+'px');
           //$('#submenu_item_'+id).css('right',(824+116-(menu_pos.left+menu_el_pos.left+($(this).width()/2)-($('#submenu_item_'+id).width()/2))+'px'));
           //$('#submenu_'+id).css('left',(menu_pos.left+menu_el_pos.left+$(this).width()/2+17-$('#submenu_'+id).width()/2)+'px');
           //alert(menu_el_pos.left);
           
           //$('#submenu_'+id).width($(this).width()+35);
           
           $('#submenu_'+id).show(500);
           
       }
        }
   });                 */
    
    /*
    $(".submenu").mouseenter(function(){
       
        
       clearTimeout(timer);
       isTimerOn = false;
       
       
      
   });
   
   $(".submenu").mouseleave(function(){
       if(!isTimerOn)
       {
        timer = setTimeout('hideSubmenuItems()',1000);   
        isTimerOn = true;
       }
       last_menu_item_id = false;
      
   });
   
   $(".menu_item").mouseleave(function(){
  //     var id= $(this).attr('id').substr(10);
          
       if(!isTimerOn)
       {
        timer = setTimeout('hideSubmenuItems()',1000);
        isTimerOn = true;
       }
       last_menu_item_id = false;
      
   });                */
   
   if($('#player').length)
   {
    flowplayer("player", "/swf/flowplayer-3.2.2.swf");    
   }
   
    
   // $.preloadImages("/images/play_hover.gif");


    /*$('li.menu').mouseover(function(){
        $(this).css('background-image','/images/menu_bg_sel.png');
        
    });*/
   

    
    $('.clear_on_focus').focus(function(){
        curr_text = $(this).attr('value');
        if($(this).attr('value')!='')
        {
            $(this).attr('value','');
        }
    }); 
    
    $('.clear_on_focus').blur(function(){

        if($(this).attr('value')=='')
        {
            $(this).attr('value',curr_text);
        }
        curr_text = '';
    }); 

 
    
     
    $(".delete_link").click(function(event)
    {
        if(!confirm("Are you sure?"))
        {
            event.preventDefault();    
        }
    });
    
    
   $('#contact_form').submit(function(event){
       
       
       /* if($('#first_name').attr('value').length<2)
        {
            alert('Please enter your first name');
            event.preventDefault();    
        }
        /*else if($('#surname').attr('value').length<2)
        {
            alert('Please enter your surname');
            event.preventDefault();    
        }   */
       
        if(!mailCheck($('#mail').attr('value')))
        {
            alert('Please enter correct email');
            event.preventDefault();    
        }
        /*
        else if($('#val_occupation').attr('value')==-1)
        {
            alert('Please select occupation');
            event.preventDefault();    
        }
        else if($('#text').attr('value').length<2)
        {
            alert('Please enter your comments');
            event.preventDefault();    
        } */          

   });
   
   
   $('#short_contact_form').submit(function(event){
       
        
        if($('#name').attr('value').length<2)
        {
            alert('Please enter your first name');
            event.preventDefault();    
        }
        
        
        
        else if($('#subj').attr('value')<5)
        {
            alert('Please type subject');
            event.preventDefault();    
        }
        

   });
               


               
     $('a#btn_send').click(function(){
         
         $('#contact_form').submit();    
     });               
   

   

   
         
});


function fixPNG(element)
{
      //Если браузер IE версии 5.5-6
  if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent))
  {
         var src;
    
    if (element.tagName=='IMG') //Если текущий элемент картинка (тэг IMG)
    {
    
      if (/\.png$/.test(element.src)) //Если файл картинки имеет расширение PNG
      {
        src = element.src;
        element.src = "/images/spacer.gif"; //заменяем изображение прозрачным gif-ом
      }
    }
    else //иначе, если это не картинка а другой элемент
    {
      //если у элемента задана фоновая картинка, то присваеваем значение свойства background-шmage переменной src
      src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
      if (src)
      {
        src = src[1]; //берем из значения свойства background-шmage только адрес картинки
        element.runtimeStyle.backgroundImage="none"; //убираем фоновое изображение
      }
    }
    //если, src не пуст, то нужно загрузить изображение с помощью фильтра AlphaImageLoader
    if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
  }
}


function mailCheck(str) {
    
    
        var at="@"
        var dot="."
        var lat=str.indexOf(at)
        var lstr=str.length
        var ldot=str.indexOf(dot)
        if (str.indexOf(at)==-1){
          /// alert("Invalid E-mail ID")
           return false
        }

        if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
           //alert("Invalid E-mail ID")
           return false
        }

        if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
            //alert("Invalid E-mail ID")
            return false
        }

         if (str.indexOf(at,(lat+1))!=-1){
            //alert("Invalid E-mail ID")
            return false
         }

         if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
            //alert("Invalid E-mail ID")
            return false
         }

         if (str.indexOf(dot,(lat+2))==-1){
            //alert("Invalid E-mail ID")
            return false
         }
        
         if (str.indexOf(" ")!=-1){
            //alert("Invalid E-mail ID")
            return false
         }

          return true            
    }
    
    function validateMessage()
    {
            var name = document.getElementById("first_name");
            var mail = document.getElementById("mail");
            
            if ((name.value.length == 0)||(!mailCheck(mail.value)))
            {
                text = "";
                
                if (name.value.length == 0)
                {
                    text+=" Name";
                }    
                
                
                if (!mailCheck(mail.value))
                {
                    if(text.length>0)
                    {
                        text+=',';
                    }
                    
                    text+=" E-Mail";
                }    
                
                alert('Please fill the following fields: '+text);
                return false;
            }
                        
            //document.getElementById('form1').submit();
            return true;
    }    
    
    function validateShortForm()
    {
            var name = document.getElementById("name");
            var phone = document.getElementById("phone");
            if ((name.value.length == 0)||(phone.value.length == 0))
            {
                text = "";
                
                if (name.value.length == 0)
                {
                    text+=" Name";
                }    
                
               
                if (phone.value.length == 0)
                {
                    if(text.length>0)
                    {
                        text+=',';
                    }
                    text+=" Phone";
                }    
                
                alert('Please fill the following fields:'+text);
                return false;
            }
                        
            //document.getElementById('form1').submit();
            return true;
    }    
    
    function trim(sInString){
sInString = sInString.replace(/ /g,' ');
return sInString.replace(/(^\s+)|(\s+$)/g, "");
}

jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}



function ___getPageSize() {
            var xScroll, yScroll;
            if (window.innerHeight && window.scrollMaxY) {    
                xScroll = window.innerWidth + window.scrollMaxX;
                yScroll = window.innerHeight + window.scrollMaxY;
            } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
                xScroll = document.body.scrollWidth;
                yScroll = document.body.scrollHeight;
            } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
                xScroll = document.body.offsetWidth;
                yScroll = document.body.offsetHeight;
            }
            var windowWidth, windowHeight;
            if (self.innerHeight) {    // all except Explorer
                if(document.documentElement.clientWidth){
                    windowWidth = document.documentElement.clientWidth; 
                } else {
                    windowWidth = self.innerWidth;
                }
                windowHeight = self.innerHeight;
            } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
                windowWidth = document.documentElement.clientWidth;
                windowHeight = document.documentElement.clientHeight;
            } else if (document.body) { // other Explorers
                windowWidth = document.body.clientWidth;
                windowHeight = document.body.clientHeight;
            }    
            // for small pages with total height less then height of the viewport
            if(yScroll < windowHeight){
                pageHeight = windowHeight;
            } else { 
                pageHeight = yScroll;
            }
            // for small pages with total width less then width of the viewport
            if(xScroll < windowWidth){    
                pageWidth = xScroll;        
            } else {
                pageWidth = windowWidth;
            }
            arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
            return arrayPageSize;
        };
        
        
        
        
        
        
        
        
      
