var is_ie = (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent));
function GID(id) { return (is_ie) ? document.all[id] : document.getElementById(id); }

$(document).ready(function() {
   if (typeof window['checkFlash'] == 'function') checkFlash();
   if ($("#gallery a[rel=fancy]").length) $("#gallery a[rel=fancy]").fancybox({ hideOnContentClick: true, overlayShow: true, overlayOpacity: 0.5, speedIn: 1000, speedOut: 600, transitionIn: 'elastic', transitionOut: 'elastic' });
   
   $( '#DirectActions' ).click(function(){
    if ( $( '#DirectionsWrappper' ).css('display') == 'none' ) {
        //$( this ).css({'background-position' : '0 -39px'}); 
        $.ajax({
            type: 'POST',
            url: "get_direction.htm",
            data: {},
            success: function(response) {
                if ( response ) {
                    $( this ).css({'background-position' : '0 -39px'}); 
                    $( '#DirectionsWrappper' ).html(response);
                    $( '#DirectionsWrappper' ).fadeIn(500); 
                    $( '.Str' ).hide();
                    ReinitScroll(); 
                    if ( $( '.Tooltip' ).length ) {
                        $( '.Tooltip' ).each(function(i){
                            if ( $( this ).find('#tItem_'+i) ) {
                                $( '#Tooltip_'+i ).easyTooltip({useElement: 'tItem_'+i});
                            }
                            if ( $( this ).find('#ltItem_'+i) ) {
                                $( '#LTooltip_'+i ).easyTooltip({useElement: 'ltItem_'+i});
                            }
                        })
                    }
                }
            }
        });
    }
    else { 
        $( this ).css({'background-position' : '0 0'}); 
        $( '#DirectionsWrappper' ).fadeOut(500); 
        $( '.Str' ).show();
    }
   })
   
   if ( $( '.scroll-pane' ).length ) {
        ReinitScroll();
    }
   
   if ( $( '.Tooltip' ).length ) {
    $( '.Tooltip' ).each(function(i){
        if ( $( this ).find('#tItem_'+i) ) {
                $( '#Tooltip_'+i ).easyTooltip({useElement: 'tItem_'+i});
        }
        if ( $( this ).find('#ltItem_'+i) ) {
                $( '#LTooltip_'+i ).easyTooltip({useElement: 'ltItem_'+i});
        }
    })
    
   }
   
   if( $( '.mycarousel' ).length ){
   $.fn.startCarousel = function() {
  		var bodywidth = $('#center2').width(),
			itemwidth = $('.mycarousel li').outerWidth(true),		
			mycontwidth = bodywidth > itemwidth ? bodywidth - bodywidth%itemwidth : itemwidth,
			licount = $('.mycarousel li').size(),
			jscroll = 1;
			
		if(licount > mycontwidth/itemwidth){
			jscroll =  mycontwidth/itemwidth;
		} else {
			jscroll = 0;
			mycontwidth = licount * itemwidth;
		}
		
		$('.mycont').width(mycontwidth);
			
    	$('.mycarousel').jcarousel({
			scroll:1,
            wrap: 'circular'
		});
  	};
	
	$(this).startCarousel();
	
	$(window).resize(function(){
		$(this).startCarousel();
	}); 
    }
    
    $('#fastForm').waypoint(function(event, direction) {
		event.stopPropagation();
	});
   
   /*$( '#fastForm' ).fancybox({
        titleShow: false,
        scrolling: 'no',
        autoScale: true,
        ajax : {
            type: "POST"
        }
    });*/
    $( '#fastFormButton' ).click(function(){
        if ($( '#hideForm' ).css('display') == 'none'){
            $( '#hideForm' ).show();
            $( '#fastForm' ).animate({'width': '370px'}, 'fast');
        }
        else $( '#fastForm' ).animate({'width': '40px'}, 'fast', function(){ $( '#hideForm' ).hide() });
    })
   
});

function ReinitScroll(){
    $('.scroll-pane').each(
        function()
        {
            $(this).jScrollPane(
                {
                    showArrows: true,
                    verticalDragMinHeight: 15, 
                    verticalDragMaxHeight: 15
                }
            );
            var api = $(this).data('jsp');
            var throttleTimeout;
            $(window).bind(
                'resize',
                function()
                {
                    if ($.browser.msie) {
                        if (!throttleTimeout) {
                            throttleTimeout = setTimeout(
                                function()
                                {
                                    api.reinitialise();
                                    throttleTimeout = null;
                                },
                                50
                            );
                        }
                    } else {
                        api.reinitialise();
                    }
                }
            );
        }
    )
}

function commitFlashObject(_obj, _container) {
   var _output = "";
   var _paramoutput = "";
   for (_cO in _obj) {
      if (_cO != "movie" && _cO != "FlashVars" && _cO != "wmode" && _cO != "quality") _output += _cO+"=\""+_obj[_cO]+"\" ";
      if (_cO != "data" && _cO != "width" && _cO != "height") _paramoutput += "<param name=\""+_cO+"\" value=\""+_obj[_cO]+"\" />\n";
   }
   var ihtm = "<object type=\"application/x-shockwave-flash\" "+_output+">\n";
   ihtm += _paramoutput;
   ihtm += "</object>\n";
   GID(_container).innerHTML = ihtm;
}

function showFlash(path, width, height, div, vars, wmode) {
   var myFlashObject = new Object;
   myFlashObject.movie = path;
   myFlashObject.data = path;
   myFlashObject.quality = "high";
   if (width) myFlashObject.width = width;
   if (height) myFlashObject.height = height;
   if (vars != "") myFlashObject.FlashVars = vars;
   if (wmode != "") myFlashObject.wmode = wmode;
   commitFlashObject(myFlashObject, div);
}

function checkFlash() {
   var flash_versions = 20; var flash_installed = 0; var flash_version = '0.0'; var java_installed = 0;
   if (navigator.plugins && navigator.plugins.length) {  // Netscape style plugin detection
      for (x = 0; x < navigator.plugins.length; x++) {
         if (navigator.plugins[x].name.indexOf('Shockwave Flash') != -1) {
            flash_version = navigator.plugins[x].description.split('Shockwave Flash ')[1];
            flash_installed = 1;
            break;
         }
      }
      for (x = 0; x < navigator.plugins.length; x++) {
         if (navigator.plugins[x].name.indexOf('Java(TM)') != -1) {
            java_installed = 1;
            break;
         }
      }
   }
   else if (window.ActiveXObject) {  // ActiveX style plugin detection
      for (x = 2; x <= flash_versions; x++) {
         try {
            oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
            if (oFlash) {
               flash_installed = 1;
               flash_version = x + '.0';
            }
         }
         catch(e) { }
      }
   }
   return flash_installed;
}

var isFlash = checkFlash();

function fnCheckSearchForm(f) {
   if (!f.search.value.match(/^.+$/)) {
      alert("Укажите поисковый запрос!");
      f.search.focus();
      return false;
   }
   return true;
}

function fnCheckSubscribeForm(f) {
   if (!f.email.value.match(/^[0-9A-Za-z\._-]+@([0-9a-z\._-]+\.)+[a-z]{2,4}$/)) {
      alert("Укажите правильно Ваш e-mail!");
      f.email.focus();
      return false;
   }
   return true;
}

function fnCheckRegistrationForm(f) {
   if (!f.fio.value.match(/(.+)/)) {
      alert("Укажите имя!");
      f.fio.focus();
      return false;
   }
   if (!f.email.value.match(/^[0-9A-Za-z._-]+@([0-9a-z_-]+\.)+[a-z]{2,4}$/)) {
      alert("Укажите правильный E-mail!");
      f.email.focus();
      return false;
   }
   if (!f.password.value.match(/(.+)/)) {
      alert("Укажите пароль!");
      f.password.focus();
      return false;
   }
   if (f.password.value != f.re_password.value) {
      alert("Подтверждение пароля не совпадает с основным паролем!");
      f.re_password.focus();
      return false;
   }
   return true;
}

function fnCheckOrders(obj) {
   var is_ok = false;
   for (i = 0; i < obj.length; i++) {
      if (obj[i].type == "text") {
         if (!obj[i].value.match(/^([1-9][0-9]*)?$/)) {
            alert("Введено некорректное значение!");
            obj[i].focus();
            return false;
         }
         if (is_ok == false) {
            if (obj[i].value) {
               is_ok = true;
            }
         }
      }
   }
   if (is_ok == false) {
      alert("Укажите количество заказываемых позиций!");
      return false;
   }
   return true;
}

function fnCheckOrderForm(f) {
   if (!f.fio.value.match(/(.+)/)) {
      alert('Укажите имя!');
      f.fio.focus();
      return false;
   }
   if (!f.phones.value.match(/(.+)/)) {
      alert('Укажите контактные телефоны!');
      f.phones.focus();
      return false;
   }
   if (!f.email.value.match(/^[a-zA-Z0-9._-]+\@[^\s:,]+\.[^\s:,]+$/i)) {
      alert('Укажите правильный e-mail!');
      f.email.focus();
      return false;
   }
   if (!f.address.value.match(/(.+)/)) {
      alert('Укажите адрес!');
      f.address.focus();
      return false;
   }
   return true;
}
