hs.graphicsDir = '/usr/system/plugins/highslide-full/graphics/';
hs.showCredits = false;
var lang="ru";
var url="";
var is_admin=0;
var is_mobile=0;

hs.registerOverlay({
	html: '<div class="closebutton" onclick="return hs.close(this)" title="Закрыть"></div>',
	position: 'top right',
	useOnHtml: true,
	fade: 2 // fading the semi-transparent overlay looks bad in IE
});

var speed_show_ul_menu=400;
var prev_elem = 0;
var is_acting = 0;
var cur_preload_page=1;
var preloaded_pages=new Array();


function show_hide_menu(id) {
   //alert(id);
   if (is_acting) return;
   is_acting=1;
   var elem=id;
   if (prev_elem) elem=prev_elem;
   ul=$("#"+elem).parent().find("ul:first");
   //alert(ul.html());
   if (ul.is(":visible")) {
      //is_child=$("#"+elem).parent().find("#"+prev_elem).length;
      is_child=$("#"+prev_elem).parent().find("#"+id).length;
      //alert(is_child);
      if (!is_child) {
         // hide elem!!
         /*while (1) {
            parent_ul = ul.parent().parent();
            if (parent_ul.length) {
               //alert(parent_ul[0].tagName);
               if (parent_ul.find("#"+id).length && !parent_ul.hasClass('lm')) {
                  //alert("2");
                  break;
               }
               if (parent_ul[0].tagName.toLowerCase()=="ul" && !parent_ul.hasClass('lm')) {
                  if (parent_ul.find("#"+prev_elem).length) {
                     ul=parent_ul;
                     //alert("1");
                     break;
                  }
                  ul=parent_ul;
                  continue;
               }
            }
            break;
         }*/
         //alert(ul.html());
         ul.slideUp(speed_show_ul_menu, function () {
            if (prev_elem) {
               if (prev_elem==ul.parent().attr('id')) {
                  alert("ok");
               }
               if (prev_elem!=id) {
                  prev_elem=0;
                  is_acting=0;
                  show_hide_menu(id);
               }
            }
            is_acting=0;
         });
      }
      else {
         prev_elem=0;
         is_acting=0;
         //alert("ok!");
         show_hide_menu(id);
      }
   }
   else {
      parent_ul=ul.parent().parent();
      arr=parent_ul.find("ul:visible:first");
      if (arr.length) {
         prev_elem=arr.parent().find("a:first").attr('id');
         is_acting=0;
         show_hide_menu(id);
         return;
      }
      ul.slideDown(speed_show_ul_menu, function () {
         prev_elem=elem;
         is_acting=0;
      });
      return;
   }
}

function hs_alert(msg) {
   id=new Date().getTime();
   $("body").append('<div class="highslide-html-content" id="s'+id+'" style="width: 400px; color: #000; height: 230px;">'+
'<div style="text-align: right;"><a href="javascript:void(0);" onclick="return hs.close(this)" style="color: #000;" id="c'+id+'">x</a></div>'+
'<div class="highslide-body" style="text-align: center;">'+
'<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p>'+
msg+
'</div>'+
'</div>');
   if (!hs.htmlExpand) {
      alert(msg);
      return;
   }
   //alert($("#s"+id).html());
   //alert(msg);
   hs.htmlExpand(null, {
      contentId: "s"+id,
      transitions: ['fade']
   });
}

function make_order(id) {
   q=$("#qty_"+id).val();
   $.ajax({
      url: "/cart/?action=add_to_cart&id="+id+"&quantity="+q+"&ajax=1",
      type: "GET",
      data: "",
      dataType: "json",
      error : function () {
         //alert("а��ИаБаКаА. а��ОаВаЕб���Е б�ОаЕаДаИаНаЕаНаИаЕ б�аИаНб�Еб�НаЕб�ОаМ.");
         //alert("Ошибка обращения к серверу!");
      },
      success : function (v) {
         //alert(v);
         if (v.cart_count || $(".cart_container").is(":visible"))
         {
            $(".cart_count").html(v.cart_count+" "+v.cart_tovarov);
            $(".total_price").html(v.total_price);
            $(".cart_container").show();
         }
         hs_alert(v.msg);
      }
   });
   return false;
}

$(document).ready(function() {
 $("body").css("width",$(window).width()+"px");
 $("#base_div_top").css("width",$(window).width()+"px");

   $(".expanding").click(function () {
      id=$(this).attr('id');
      show_hide_menu(id);
   });
});

$(document).ready(function() {
   
});

function openYouTube(opener) {
	var returnValue;
	
	// Safari Mobile doesn't have Flash, so we just let the device use the built-in 
	// YouTube viewer.
	
		
	if (/(iPhone|iPod|iPad)/.test(navigator.userAgent)) {
		opener.href = opener.href.replace('/v/', '/watch?v=');
		returnValue = true;		
	}

   /*
	else returnValue = hs.htmlExpand(opener, { 
		objectType: 'swf', 
		objectWidth: $(opener).attr("swfwidth"), 
		objectHeight: $(opener).attr("swfheight"), 
		width: $(opener).attr("swfwidth"), 
		swfOptions: { 
			params: { 
				allowfullscreen: 'true' 
			}
		}, 
		wrapperClassName: 'draggable-header',
		maincontentText: 'You need to upgrade your Flash player' 
	});
	*/

	else returnValue = hs.htmlExpand(opener, { 
		objectType: 'iframe', 
		objectWidth: $(opener).attr("swfwidth"), 
		objectHeight: $(opener).attr("swfheight"), 
		width: $(opener).attr("swfwidth"), 
		swfOptions: { 
			params: { 
				allowfullscreen: 'true' 
			}
		}, 
		wrapperClassName: 'draggable-header'
		//maincontentText: 'You need to upgrade your Flash player' 
	});
	
	return returnValue;
}  

function update_events() {
   if (!is_admin && !is_mobile)
   {
      $(".g_title, .portf_item_img, .pages_nav a, .cont .back").click(function () {
         nav($(this).attr("href"), $(this));
         return false;
      });
   }
   $("a.highslide").click(function() {
      return hs.expand(this);
   });
   var valed=false;
   $(".cont_butt").click(function() {
      if ($.validationEngine && !valed) {
         $(".valForm").validationEngine({
            ajaxSubmit: true,
            ajaxSubmitFile: $(".valForm").attr('action')
         });
         valed=true;
      }
      $("#order_form").submit();
      return false;
   });
   $("a.youtube").click(function() {
      openYouTube(this);
      return false;
   });
   $("input[type=button]").each(function () {
      if ($(this).attr('href') && !$(this).hasClass('order')) {
        $(this).click(function () {
           window.location.href=$(this).attr('href');
        });
      }
   });
   $(".order").click(function() {
      make_order($(this).attr('rel'));
      return false;
   });
   $(".go_search").click(function() {
      $("#top_search").submit();
      return false;
   });
}

// contacts

$(document).ready(update_events);

var ind_now=0;
var ind_next=1;
var animating=false;
var min_h=650;
var prev_min_h=0;
var now_h=0;
//var first_html=$(".contents:eq(0)").html();
var first_html='<div class="cont_top"></div><div class="cont"></div><div class="cont_bott"></div>';
var is_first_nav=true;

function nav(this_href, elm, is_search)
{
   if (!is_search)
   {
      $("#search_form input[name=keywords]").val("");
   }
   else
   {
      $("#top_menu li a").removeClass('act');
   }
   var is_portf=false;
   if (elm) if (elm.hasClass('g_title') || elm.hasClass('portf_item_img') || elm.hasClass('back')) is_portf=true;
   //if ($(this).hasClass('act')) return false;
   //if ($.browser.msie) is_portf=false;
   if (animating) return false;
   animating=true;
   var h=this_href;
   if (elm) $("#top_menu li a").removeClass('act');
   if (elm) elm.addClass('act');
   window.location.hash=this_href.replace('http://www.appmania.ua', '');
   if (elm)
   {
      ind_next=$("#top_menu li").index(elm.parent());
      if (is_portf && ind_now<100) ind_now=0;
      if (elm.attr("rel"))
      {
         ind_next=100+parseInt( elm.attr("rel") );
         if (ind_now<100) ind_now=1;
      }
   }
   else
   {
      ind_next=ind_now;
   }
   var now=$(".contents:eq(0)");
   var prev_h=now.outerHeight();
   var next=$("<div></div>");
   next.appendTo('#base_div_bott');
   next.addClass('contents').hide().html(first_html);
   var l=now.offset().left;
   var t=now.offset().top;
   var o={
      duration: 500,
      queue: false,
      complete: function ()
      {
         if ($.browser.msie) this.style.removeAttribute('filter');
      }
   };
   //if (is_portf) o.duration*=500;
   
   function p_done(v) {
         v=v.replace(/<script>.*<\/script>/, '');
         next.find(".cont").html(v).show();
         
         var df=next.find(".cont").find("input[name=kw]");
         if (df.length)
         {
            $("#search_form input[name=keywords]").val(df.val());
         }
         
         if (v.indexOf('portf_item')>0)
         {
            next.find(".cont").attr("id", "portfolio");
            next.css('paddingLeft', '-15px');
            next.find(".cont_top").remove();
            next.find(".cont_bott").remove();
         }
         
         if (next.find("#is_portf").length)
         {
            next.addClass('nobg');
         }
         
         var new_h=next.outerHeight();
         //alert(new_h+next.html());
         
         if (new_h<min_h)
         {
            new_h=min_h;
            var w_h=0;
            w_h+=next.find('.cont_top').outerHeight();
            w_h+=next.find('.cont_bott').outerHeight();
            next.find('.cont').css('height', new_h-w_h);
            //alert("!");
         }
         else
         {
            //next.find('.cont').css('height', 'auto');
         }
         //new_h=next.outerHeight();
         new_h=next.outerHeight();
         //alert(new_h);
         next.hide();
         var delta=(prev_h-new_h);
         //alert(prev_h+"-"+new_h+"="+delta);
         resize_window();
         
         if (v.indexOf('portf_item')>0)
         {
            new_h-=8;
            if ($.browser.opera) new_h-=10;
         }
         
         //var dur=500;
         var dur=500;
         if ($(".hidden").length) dur=1;
         
         var fn=function () {
         
         $("#base_div_bott").animate({
            //'height': (now_h-delta)+"px"
            'height': ($("#musthead").outerHeight() + $("#bott_div").outerHeight() + new_h)+"px"
         }, {
            duration: 100,
            step: function (now) {
               $("#bott_div").css('top', (now-158)+"px");
               update_fonar();
            },
            complete: function ()
            {
               
               //alert("now="+ind_now+"; ind_next="+ind_next);
            
               //alert(is_portf);
            
               if (!is_portf)
               {
            
                  if (ind_next>ind_now)
                  {
                     var css_now={
                        position: 'absolute',
                        left: l
                     };
                     var css_next={
                        left: $(document).width(),
                        top: t,
                        position: 'absolute'
                     };
                     var anim_now={
                        left: -now.width()
                     };
                     var anim_next={
                        left: l
                     };
                  }
                  else
                  {
                     var css_now={
                        position: 'absolute',
                        left: l
                     };
                     var css_next={
                        left: -now.width(),
                        top: t,
                        position: 'absolute'
                     };
                     var anim_now={
                        left: $(document).width()
                     };
                     var anim_next={
                        left: l
                     };
                  }
                                 
                  now_h-=delta;
                  now.css(css_now).animate(anim_now, {
                     duration: dur,
                     queue: false,
                     complete: function ()
                     {
                        now.remove();
                        animating=false;
                     }
                  });
                  next.css(css_next).show().animate(anim_next, o);
               }
               else
               {
                  o.duration/=2;
                  var a1=23;
                  var a2=25;
                  
                  var css_now={
                     position: 'absolute',
                     left: l
                  };
                  var css_next={
                     position: 'absolute',
                     width: elm.width(),
                     height: elm.outerHeight(),
                     left: elm.offset().left-a1,
                     top: elm.offset().top-a2,
                     opacity: 0
                  };
                  var anim_now={
                     //left: $(document).width()
                     opacity: 0
                  };
                  var anim_next={
                     //left: l
                     width: next.width(),
                     height: next.outerHeight(),
                     left: l,
                     top: t,
                     opacity: 1
                  };
                  
                  if (elm) if (elm.hasClass('back'))
                  {
                     
                     var css_now={
                        position: 'absolute',
                        left: l
                     };
                     var css_next={
                        position: 'absolute',
                        width: next.width(),
                        height: next.outerHeight(),
                        opacity: 1,
                        left: l,
                        top: t
                     };
                     
                     next.css(css_next);
                     var fg=$(".portf_item_img[rel="+elm.attr("rel")+"]");
                     if (fg.length) elm=fg;
                     next.show();
                     //alert(elm.attr("rel")+"!: "+elm.offset().left+" "+elm.offset().top+"\n"+elm.parent().html());
                     //return;
                       
                     var anim_next={
                        //left: $(document).width()
                        opacity: 1
                     };
                     var anim_now={
                        //left: l
                        width: elm.width(),
                        height: elm.outerHeight(),
                        left: elm.offset().left-a1,
                        top: elm.offset().top-a2
                     };
                     
                     next.css('opacity', 0);
                  }
                                 
                  now_h-=delta;
                  now.css(css_now).animate(anim_now, {
                     duration: dur,
                     queue: false,
                     complete: function ()
                     {
                        now.remove();
                        animating=false;
                     }
                  });
                  next.css(css_next).show().animate(anim_next, o);
               }
               
               ind_now=ind_next;
               
               $(".hidden").removeClass('hidden');
               
               update_events();
               
               try {
                  var pageTracker = _gat._createTracker("UA-9572183-20");
                  pageTracker._trackPageview(h);
                  //alert("Track "+h);
               } catch (err) { }
               
            }
         });
         
         }
         
         if (is_portf && false)
         {
            now.animate({ opacity: 0 }, { duration: 500, complete: function () {
               now.hide();
            } });
            fn();
         }
         else
         {
            fn();
         }
      };
   
   var gh="";
   if (elm)
   {
      if (elm.attr("num"))
      {
         m=parseInt( elm.attr("num") );
         gh=preloaded_pages[m];
      }
   }
   
   if (!gh) {   
      $("#loading").css({
         top: $(".contents").offset().top+20,
         left: $(".contents").offset().left+$(".contents").width()/2-$("#loading").width()/2
      }).fadeIn(100);
      //return;
      $.ajax({
         url: h+(h.indexOf('?')>0 ? "&" : "?")+"ajax=1",
         type: "GET",
         data: "",
         //dataType: "json",
         cache: true,
         error : function () {
            //alert("Ошибка сети");
         },
         success : function (v)
         {
            $("#loading").fadeOut(100);
            p_done(v);
         } 
      });
   }
   else
   {
      //alert("this page is cached");
      p_done(gh);
   }
}

function resize_window()
{

 $("body").css("width",$(window).width()+"px");
 $("#base_div_top").css("width",$(window).width()+"px");

   var o_bott={
      position: 'absolute',
      //left: (($(document).width()-898)/2)+'px'
      left: 0
   };
   var o_lang={
      position: 'absolute',
      left: (($(window).width()-47+16)/2)+'px'
   };
   if ($(window).width()<950)
   //if (1)
   {
      var o_c={
         left: (($(window).width()-950)/2)+'px'
      };
      $(".contents").css(o_c);
   }
   update_fonar();
   /*
   if ($(window).width()<1286)
   {
      o_bott.left=0;
   }
   else
   {
      o_lang.position='static';
      o_lang.left=0;
   }
   */
   $("#bott_div").css(o_bott);
   $("#bott_div ul").css(o_lang);
   return false;
}

function resize_window2()
{
   resize_window();
   var o_bott={
      position: 'absolute',
      //left: (($(document).width()-898)/2)+'px'
      left: 0
   };
   var o_lang={
      position: 'absolute',
      left: (($(window).width()-47+16)/2)+'px'
   };
   if ($(window).width()<950 || true)
   {
      var o_c={
         left: (($(window).width()-950)/2)+'px'
      };
      $(".contents").css(o_c);
   }
   /*
   if ($(window).width()<1286)
   {
      o_bott.left=0;
   }
   else
   {
      o_lang.position='static';
      o_lang.left=0;
   }
   */
   $("#bott_div").css(o_bott);
   $("#bott_div ul").css(o_lang);
   return false;
}

var fonar_started=false;

function anim_fonar(e)
{  
   e.animate({
      opacity: !parseInt(e.css('opacity')) ? 1 : 0
   }, {
      duration: 3000,
      complete: function () {
         anim_fonar(e);
      }
   });
}

function update_fonar()
{

	var deviceAgent = navigator.userAgent.toLowerCase();
	var agentID = deviceAgent.match(/(iphone|ipod)/);
	if (agentID) {
	   $("#fonar_l_s, #fonar_l_b, #fonar_r_b, #fonar_r_s").hide();
	   return;
	}


   $("#fonar_l_s").css({
      left: (($(window).width()-$(".contents").width())/2-195)+"px"
   });
   $("#fonar_l_b").css({
      left: (($(window).width()-$(".contents").width())/2-20)+"px"
   });
   $("#fonar_r_s").css({
      left: (($(window).width()-$(".contents").width())/2+$(".contents").width()+110)+"px"
   });
   $("#fonar_r_b").css({
      left: (($(window).width()-$(".contents").width())/2+$(".contents").width()-57)+"px"
   });
   if (!fonar_started)
   {
      $("#fonar_l_s, #fonar_l_b, #fonar_r_b, #fonar_r_s").each(function () {
         if ($.browser.msie) return;
         //return;
         $(this).css({
            opacity: 0
         });
         anim_fonar($(this));
      });
      fonar_started=true;
   }
}

function preload_pages() 
{
   var e=$("#top_menu li a:eq("+(cur_preload_page-1)+")");
   if (!e.length) return;
   var h=e.attr("href");
   h=h+(h.indexOf('?')>0 ? "&" : "?")+"ajax=1",
   //alert(h);
   $.ajax({
      url: h,
      type: "GET",
      data: "",
      cache: true,
      //dataType: "json",
      success : function (v) {
          //alert(cur_preload_page+"= "+v);
          preloaded_pages[cur_preload_page]=v;
          e.attr("num", cur_preload_page);
          //alert(e.find("span").html()+" загружена");
          cur_preload_page++;
          preload_pages();
      }
   });
}

$(function () {

   var userAgent = navigator.userAgent.toLowerCase();
   $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
   if (!$.browser.chrome) $("#search_form input").placeholder();

   update_fonar();

   if (is_admin || is_mobile)
   {
      $(".hidden").removeClass('hidden');
      return;
   }
   
   $("#search_form").submit(function ()
   {
      var h="";
      h=$(this).attr("action")+"?";
      var i=0;
      $(this).find("input[name]").each(function ()
      {
         if (i) h+="&";
         h+=$(this).attr("name")+"="+encodeURIComponent($(this).val());
         i++;
      });
      nav(h, null, 1);
      return false;
   });
   
   $(".search_butt").click(function () {
      $("#search_form").submit();
      return false;
   });

   $(window).resize(resize_window2);

   prev_min_h=parseInt( $("#base_div_bott").css('minHeight').replace('px', '') );
   $("#base_div_bott").css('minHeight', '0').css('min-height', '0');
   now_h=$("#base_div_bott").outerHeight();
   $("#base_div_bott").css('height', now_h+'px');
   
   var prev_h=window.location.hash.replace('#', '');
   if (url!=prev_h && prev_h && !is_admin)
   {
      //alert("you refreshed the page!");
      $("#top_menu li a").each(function ()
      {
         if ($(this).attr("href")==prev_h)
         {
            $("#top_menu li a").removeClass('act');
            $(this).addClass('act');
            //alert("!");
         }
      });
      nav(prev_h);
   }
   else
   {
      $(".hidden").removeClass('hidden');
   }
   
   $("#top_menu li a").click(function () {
      if (is_admin) return true;
      if (window.location.hash.replace('#', '')==$(this).attr("href")) return false;
      nav($(this).attr("href"), $(this));
      return false;
   });   
   
   preload_pages();
   
   $(".lang_rus, .lang_eng").click(function ()
   {
      return true;
      if (is_admin) return true;
      var h=window.location.hash.replace('#', '');
      if (!h) h=window.location.href;
      else h='http://www.appmania.ua'+h;
      //alert(h); return false;
      h=h.replace('http://www.appmania.ua/ru', '');
      h=h.replace('http://www.appmania.ua/en', '');
      h=h.replace('http://www.appmania.ua', '');
      //h=h.replace(/^\/{1}/, 'http://www.appmania.ua/'+($(this).hasClass('lang_rus') ? 'ru/' : ''));
      h=h.replace(/^\/{1}/, ($(this).hasClass('lang_rus') ? 'http://www.appmania.ua/' : 'http://www.appmania.org/')+''+($(this).hasClass('lang_rus') ? '' : ''));
      //alert(h); return false;
      h = "http://appmania.org/";
      window.location.href=h;
      return false;
   });
});

