var ival = null;

function moveToImage(cont,direction) {
  $("#fullimage").attr("gallery_id",$(cont).attr("gallery_id"));
  var cur_img = $(">.selected",cont).removeClass("selected")[0];
  if (!cur_img)
    cur_img = $(">a:first",cont)[0];
  if (!cur_img)
    return false;    
  switch(direction) {
    case -1:
      if ($(cur_img).prev()[0])
        cur_img = $(cur_img).prev()[0];
      else
        cur_img = $(">a:last",cont)[0];
      break;
    case +1:
      if ($(cur_img).next()[0])
        cur_img = $(cur_img).next()[0];
      else
        cur_img = $(">a:first",cont)[0];
      break;
  }
  $(cur_img).addClass("selected");
  var img_index = $(">a",cont).index(cur_img)+1;
  $("#fullimage .pager .page").text(img_index);
  $("#fullimage .pager .pages").text($(">a",cont).length);
  	var fw = parseInt($(cur_img).attr("rw"));
  	var fh = parseInt($(cur_img).attr("rh"));
    var txt = $(cont).parent().find(">h2").text();
    fh+=15;
    if (txt!="") {
      fh+=30;
      $("#fullimage .fullimagedesc").text(txt).show();
    } else { 
      $("#fullimage .fullimagedesc").text("").hide();
      fh+=10;
    }
  	setImageHeight(fw,fh);
  	$("#fullimage .loading").hide();
  	$("#fullimage .loading img").hide();
  	var full_image  = $("#fullimage > img.full")[0];
  	ival = setInterval(function() { 
  			$("#fullimage .loading").show();
  			$("#fullimage .loading img").show();
  			$(full_image).hide();
  			clearInterval(ival); 
  			ival = null; 
  		},100);
  	$.preload([ $(cur_img).attr("href") ], {
  		onFinish: function(data) {
  			clearInterval(ival);
  			ival = null;
  			$("#fullimage > .loading").hide(); 
  			$(full_image).attr({ "src":data.image }).fadeIn(300);
      } 
    });


}

function onGalleryToggler() {
    $("#fullimage .pager").show();
    var cont = $(this).parent().find(">.photos")[0];
		$("#overlay").css("opacity",0).show().fadeTo(500,0.9);
    moveToImage(cont,0);
    return false;
  }

function bindImages() {
  $(".photos-cont .toggler").click(onGalleryToggler);
  $(".photos-cont .image-toggler").click(function() {
    $(this).parent().find(".toggler:first").trigger("click");
  });
  $("#fullimage .full").click(function() {
    var gallery_id = $("#fullimage").attr("gallery_id");
    var cont = $(".photos-cont .photos[gallery_id="+gallery_id+"]")[0];
    moveToImage(cont,+1);
    return false;
  });  
  $("#fullimage .nav .prev").click(function() {
    var gallery_id = $("#fullimage").attr("gallery_id");
    var cont = $(".photos-cont .photos[gallery_id="+gallery_id+"]")[0];
    moveToImage(cont,-1);
    return false;
  });
  $("#fullimage .nav .next").click(function() {
    var gallery_id = $("#fullimage").attr("gallery_id");
    var cont = $(".photos-cont .photos[gallery_id="+gallery_id+"]")[0];
    moveToImage(cont,+1);
    return false;
  });
}




var isAPILoaded = false;
var lang='ru';

function showMap() {


  function CustomMarker(latlng,  map) {
    google.maps.OverlayView.call(this);

    this.latlng_ = latlng;

    // Once the LatLng and text are set, add the overlay to the map.  This will
    // trigger a call to panes_changed which should in turn call draw.
    this.setMap(map);
  }

  CustomMarker.prototype = new google.maps.OverlayView();

  CustomMarker.prototype.draw = function() {
    var me = this;

    // Check if the div has been created.
    var div = this.div_;
    if (!div) {
      // Create a overlay text DIV
      div = this.div_ = document.createElement('DIV');

      $(div).css({position:"absolute","white-space":"nowrap", background:"#5c5954",padding:"12px 17px",color:"#fff"}).text(lang=="en" ? "Angel" : "Салон красоты \"Ангел\"");

      // Then add the overlay to the DOM
      var panes = this.getPanes();
      panes.overlayLayer.appendChild(div);
    }

    // Position the overlay 
    var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
    if (point) {
      div.style.left = (point.x-70) + 'px';
      div.style.top = (point.y+10) + 'px';
    }
  };

  CustomMarker.prototype.remove = function() {
    // Check if the overlay was on the map and needs to be removed.
    if (this.div_) {
      this.div_.parentNode.removeChild(this.div_);
      this.div_ = null;
    }
  };


  $("#fullimage #map").show();  
// 	$("#fullimage .loading").hide();
  var ll = new google.maps.LatLng(55.751658, 37.858171);
  var map = new google.maps.Map(document.getElementById("map"),{
    center:ll,
    zoom:15,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    navigationControl: true,
    mapTypeControl: false,
    navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL}
  });  
  google.maps.event.addListener(map,
    'tilesloaded', function() {
    	$("#fullimage .loading").hide();
    	$("#fullimage #map").show();
    }); 
  var point = new google.maps.LatLng(55.750658, 37.858171);
  var marker = new google.maps.Marker({
    position: point,
    map: map
  });
  overlay = new CustomMarker(point, map);
}

function loadMap() {
  google.load("maps", "3.x", {"callback" : showMap,other_params:"sensor=false&hl="+lang });  
}
  
function initLoader() {
   var script = document.createElement("script");  
   script.src = "http://www.google.com/jsapi?key=ABQIAAAA1ZfSf4A_YequRMYC5yamDBQQmGHo0YDrG51S2Clkeu74s6faOxRyk_NbRC5u0aH5_hN9iEFXoQiGIg&callback=loadMap&hl="+lang;  
   script.type = "text/javascript";  
   document.getElementsByTagName("head")[0].appendChild(script);  
}
  

function bindPageScroller() {
  $(".scrollable").jScrollPane({
    scrollbarWidth:7,
    reinitialiseOnImageLoad: true,
    showArrows:true,
    arrowSize:20,
    scrollbarMargin:30       
  });
  if ($(".scrollable:first").parent().find(">.jScrollPaneTrack")[0]) {
  $("#nav-page .down").click(function() {
    if ($(".jScrollPaneContainer > div:first")[0])                              
     $(".jScrollPaneContainer > div:first")[0].scrollBy(300);
  });  
  $("#nav-page .up").click(function() {                              
    if ($(".jScrollPaneContainer > div:first")[0])                              
     $(".jScrollPaneContainer > div:first")[0].scrollBy(-300);
  });
  } else {
    $("#nav-page .up,#nav-page .down").hide();
  }
}

function bindGalleryImages() {
  $("a.single_image").click(onGalleryImageClick);
}

function setImageHeight(w,h) {
	if (w>0 && h>0) {
		var fh = h;
		var fw = w;
		$("#fullimage .loading").css({
		  left:0,
			height:Math.round(fh)+13,
			width:Math.round(fw)+30
		});
		$("#fullimage").css({ height:Math.round(fh)-1,"margin-top":Math.round(-fh/2-20) }).show();
		$("#fullimage_close").css({ "margin-top":Math.round(-fh/2-40) }).show();
 		if ($.browser.safari) {
  		  $("#fullimage").css({ 
  			marginLeft:Math.round(-fw/2),
  			width:Math.round(fw)
  		});
  		$("#fullimage_close").css({ "margin-left":Math.round(fw/2-80) }).show();
		} else { 
  		  $("#fullimage").animate({ 
  			marginLeft:Math.round(-fw/2),
  			width:Math.round(fw)
  		}, 500 );
  		  $("#fullimage_close").animate({ 
  			marginLeft:Math.round(fw/2-80)
  		}, 500 );
	  }
		$("#fullimage .loading img").css({ "margin-top":Math.round((fh-1))/2-32 });
	}
}

function closeGallery() {
	$("#fullimage .loading").stop();
	$("#fullimage").stop().css({ width:2,height:150,"margin-left":-1,"margin-top":-1 }).hide();
	$("#fullimage_close").stop().css({ "margin-left":-1,"margin-top":-1 }).hide();
	$("#fullimage > img.full").hide();
	$("#fullimage").stop();
	$("#overlay").fadeOut(500);
	return false;
};

var ival = null;

function onGalleryImageClick() {
    $("#fullimage .pager").hide();
  	var fw = parseInt($(this).attr("rw"));
  	var fh = parseInt($(this).attr("rh"));
    var txt = $(this).attr("title");
    if (txt) {
      fh+=38;
      $("#fullimage .fullimagedesc").text(txt).show();
    } else 
      $("#fullimage .fullimagedesc").text("").hide();
  	setImageHeight(fw,fh);
		$("#overlay").css("opacity",0).show().fadeTo(500,0.9);
  	$("#fullimage .loading").hide();
  	$("#fullimage .loading img").hide();
  	var full_image  = $("#fullimage > img.full")[0];
  	ival = setInterval(function() { 
  			$("#fullimage .loading").show();
  			$("#fullimage .loading img").show();
  			$(full_image).hide();
  			clearInterval(ival); 
  			ival = null; 
  		},100);
  	$.preload([ $(this).attr("href") ], {
  		onFinish: function(data) {
  			clearInterval(ival);
  			ival = null;
  			$("#fullimage > .loading").hide(); 
  			$(full_image).attr({ "src":data.image }).fadeIn(300);
      } 
    });
    return false;
  }

function bindMap() {
  if (!$("#content .googlemap-link")[0])
    return;
    
  $("#content .googlemap-link").click(function(e) {
		if ($.browser.safari) {
      $("#close_fullimage,#fullimage").css({ "position":"absolute" });		
    }
		$("#overlay").css("opacity",0).show().fadeTo(500,0.9);
		
  	if ($.browser.safari)
  	 $("#close_fullimage").css({ marginLeft:320 }).show();
    else
  	 $("#close_fullimage").show().animate({ marginLeft:320},500);
  	
		$("#fullimage").show();
   	$("#fullimage .loading").css({ "z-index":10,position:"absolute" }).show();
   	$("#fullimage .loading img").show();
		setImageHeight(600,470,"");
		e.returnValue = false;
    var iiii = setInterval(function() {		
      if (!isAPILoaded) {
        initLoader();
      } else 
        loadMap();
      clearInterval(iiii);
      iiii = null;
    },500);      
    return false;
  });
}

function checkContactForm() {
  var name = jQuery("#contact-form input[name='contact_name']")[0].value;
  if (name=="Имя")
    name="";  
  var email = jQuery("#contact-form input[name='contact_email']")[0].value;
  if (email=="E-mail")
    email="";  
  var text = jQuery("#contact-form textarea[name='contact_text']")[0].value;
  if (text=="Комментарий")
    text="";
  jQuery("#contact-form .error").hide();
  if (!name || !email || !text) {
    if (!name) {
      jQuery(".error",jQuery("#contact-form input[name='contact_name']").parent()[0]).show();
      jQuery("#contact-form input[name='contact_name']").focus();
      return false;
    }      
    if (!email) {
      jQuery(".error",jQuery("#contact-form input[name='contact_email']").parent()[0]).show();
      jQuery("#contact-form input[name='contact_email']").focus();
      return false;
    }      
    if (!text) {
      jQuery(".error",jQuery("#contact-form textarea[name='contact_text']").parent()[0]).show();
      jQuery("#contact-form textarea[name='contact_text']").focus();
      return false;
    }      
    return false;
  }
  return true;  
}

function bindContactForm() {
  if (!jQuery("#contact-form")[0])
    return;
  jQuery("#contact-form").submit(checkContactForm);
  jQuery("#contact-form .reset").click(function() {
    jQuery("#contact-form .error").hide();
  });
  jQuery("#contact-form button[name='contact_post']").click(checkContactForm);
  jQuery("#contact-form input[name='contact_name']")
    .bind("focus",function() { if (this.value=="Имя" || this.value=="Name") this.value=""; }).bind("blur",function() { if (this.value=="") this.value=(lang=="ru" ? "Имя" : "Name"); });
  jQuery("#contact-form input[name='contact_email']")
    .bind("focus",function() { if (this.value=="E-mail" ) this.value=""; }).bind("blur",function() { if (this.value=="") this.value="E-mail"; });
  jQuery("#contact-form textarea[name='contact_text']")
    .bind("focus",function() { if (this.value=="Комментарий" || this.value=="Comments") this.value=""; }).bind("blur",function() { if (this.value=="") this.value=(lang=="ru" ? "Комментарий" : "Comments"); });
}

var menu_timer = null;

function showSubpage(subpages_cont) {
  $("#cur-subpages").hide();
  $("#all_subpages ul").hide();
  $(subpages_cont).show(); 
}

function hideSubpage() {
  $("#header").stop(true,true);
  if (!$("#main").hasClass("wide-header") && parseInt($("#header").css("width"))>260) {
    $("#header").animate({ width:260 },250);
  }
  $("#cur-subpages").show();
  $("#all_subpages ul").hide();
}


function bindMenu() {
  $("#primary").hover(function() {
    $("#sidebar .current_page_parent").removeClass("current_page_parent").addClass("current_page_parent_tmp");
    $("#sidebar .current_page_item").removeClass("current_page_item").addClass("current_page_item_tmp");
    $("#sidebar .current_page_ancestor").removeClass("current_page_ancestor").addClass("current_page_ancestor_tmp");
  },function() {
    hideSubpage();
    $("#sidebar .current_page_parent_tmp").removeClass("current_page_parent_tmp").addClass("current_page_parent");
    $("#sidebar .current_page_item_tmp").removeClass("current_page_item_tmp").addClass("current_page_item");
    $("#sidebar .current_page_ancestor_tmp").removeClass("current_page_ancestor_tmp").addClass("current_page_ancestor");
  });
  $(".subpages").hover(function() {
    if ($("#primary").is(".main-page"))
      $("#primary").addClass("curlight");
    $(".current_page_item",this).removeClass("current_page_item").addClass("current_page_item_tmp");
    $(".current_page_ancestor",this).removeClass("current_page_ancestor").addClass("current_page_ancestor_tmp");
    var sid = $(this).attr("id");
    if (sid=="cur-subpages") {
      $("#sidebar .current_page_ancestor_tmp,#sidebar .current_page_ancestor").addClass("jsover");
    } else {
      sid = sid.replace("subpage_of_","");
      $("#sidebar .page-item-"+sid).addClass("jsover");
    }
  },function() {
    if ($("#primary").is(".main-page"))
      $("#primary").removeClass("curlight");
    $(".current_page_item_tmp",this).removeClass("current_page_item_tmp").addClass("current_page_item");
    $(".current_page_ancestor_tmp",this).removeClass("current_page_ancestor_tmp").addClass("current_page_ancestor");
    $("#sidebar .current_page_item_tmp").removeClass("current_page_item_tmp").addClass("current_page_item");
    $("#sidebar .current_page_ancestor_tmp").removeClass("current_page_ancestor_tmp").addClass("current_page_ancestor");
    hideSubpage();
    var sid = $(this).attr("id");
    if (sid=="cur-subpages") {
      $("#sidebar .current_page_ancestor_tmp,#sidebar .current_page_ancestor").removeClass("jsover");
    } else {
      sid = sid.replace("subpage_of_","");
      $("#sidebar .page-item-"+sid).removeClass("jsover");
    }
  });
  $(".subpages li").hover(function() {
    $(this).addClass("jsover");
  },function() {
    $(this).removeClass("jsover");
  });  
  $("#sidebar li").click(function() {
    var page_id = parseInt($(this).attr("class").replace("page_item","").replace("current_page_item","").replace("current_page_ancestor","").replace("current_page_parent","").replace("page-item-",""));
    if (page_id>0 && $("#all_subpages #subpage_of_"+page_id)[0]) {
      return false;
    }
    return true;  
  }).hover(function() {
    if ($("#primary").is(".main-page"))
      $("#primary").addClass("curlight");
    $(this).addClass("jsover");
    if ($(this).hasClass("current_page_item") || $(this).hasClass("current_page_parent")) {
      hideSubpage();    
      return;
    }
    var page_id = parseInt($(this).attr("class").replace("page_item","").replace("current_page_item","").replace("current_page_ancestor","").replace("current_page_parent","").replace("page-item-",""));
      $("#sidebar .current_page_parent").removeClass("current_page_parent").addClass("current_page_parent_tmp");
      $("#sidebar .current_page_item").removeClass("current_page_item").addClass("current_page_item_tmp");
      $("#sidebar .current_page_ancestor").removeClass("current_page_ancestor").addClass("current_page_ancestor_tmp");
    if (page_id>0 && $("#all_subpages #subpage_of_"+page_id)[0]) {
      var subpages_cont = $("#all_subpages #subpage_of_"+page_id)[0];
      $("#header").stop(true,true);
      if (!$("#main").hasClass("wide-header") && parseInt($("#header").css("width"))<375) {
        $("#header").animate({ width:375 },250);
      };
      if (menu_timer) {
        clearInterval(menu_timer);
        menu_timer = null;
      }
      showSubpage(subpages_cont);
    } else {
      hideSubpage();
      $("#cur-subpages").css("opacity",0.3);
    }
  },function() {
      $(this).removeClass("jsover");
      $("#cur-subpages").css("opacity",1);
      if ($("#primary").is(".main-page"))
        $("#primary").removeClass("curlight");
      if (menu_timer) {
        clearInterval(menu_timer);
        menu_timer = null;
      }
      menu_timer = setInterval(function() {
        hideSubpage();
      },500);
  });
  $("#all_subpages ul,#cur-subpages").hover(function() {
      if (menu_timer) {
        clearInterval(menu_timer);
        menu_timer = null;
      }
  },function() {
      if (menu_timer) {
        clearInterval(menu_timer);
        menu_timer = null;
      }
      menu_timer = setInterval(function() {
        hideSubpage();
      },500);
  });
}

var mni = null;

function changeMainNews() {
  var cur_el = $("#main-textblock .showed")[0];
  if (!cur_el)
    cur_el = $("#main-textblock a:first")[0];
  var next_el = $(cur_el).next()[0];
  if (!next_el)
    next_el = $("#main-textblock a:first")[0];  
  if (mni) {
    clearInterval(mni);
    mni = null;
  }
  $(cur_el).animate({ top:-73 },1500,function() {
    $(this).removeClass("showed");
  });
  $(next_el).css("top",73).addClass("showed").animate({ top:0 },1500,function() {
      mni = setInterval(function() {
            changeMainNews();
          },4000);
  });
}

function bindMainNews() {
  $("#main-textblock a:first").addClass("showed").show();
  mni = setInterval(function() {
        changeMainNews();
      },4000);
}
    
$(document).ready(function() {
	$("#overlay,#fullimage_close a").click(closeGallery);
  bindGalleryImages();
  bindPageScroller();
  $("#maingalleryview").cycle({
    fx:'fade',
    timeout:4000
  });
  bindMap();
  bindContactForm();
  bindMenu();
  bindMainNews();
  bindImages();
  $("#subscribe-form input[name=email]").focus(function() {
    if (this.value=='E-mail')
      this.value='';
  }).bind("blur",function() {
    if (this.value=='')
      this.value='E-mail';
  });
  $("#subscribe-form button.subscribe").click(function(e) {
    var email = $("#subscribe-form input[name=email]")[0].value;
    if (!email || email=='E-mail') {
      $("#subscribe-form .error").text("Ошибка: поле E-mail не заполнено").show();
      $("#subscribe-form input[name=email]").trigger("focus");      
      return false;
    }
    $("#subscribe-form .error").hide();
    return true;
  });
  $("#subscribe-form .unsubscribe").click(function() {
    var email = $("#subscribe-form input[name=email]")[0].value;
    if (!email || email=='E-mail') {
      $("#subscribe-form .error").text("Ошибка: поле E-mail не заполнено").show();
      $("#subscribe-form input[name=email]").trigger("focus");      
      return false;
    }
    $.get("/maillist/index.php",{ action:'unsub',addr:email},function(res) {
      if (res=="OK") {
        $("#subscribe-form form").html("Адрес "+email+" был успешно исключен из списка рассылки.");
      } else {
        $("#subscribe-form .error").text("Ошибка: произошла ошибка, возможно неправильно указан e-mail").show();
      }
    });
    return false;
  });
});			

