var isAPILoaded = false;
var qqival = null;
var ival2 = null;

function bindKeys() {
    jQuery.hotkeys.remove("right");
    jQuery.hotkeys.remove("left");
    jQuery.hotkeys.add("right",{ type:"keydown" },function() {
      jQuery("#gal .arrows .right").trigger("click");
    });
    jQuery.hotkeys.add("left",{ type:"keydown" },function() {
      jQuery("#gal .arrows .left").trigger("click");
    });
}

function getSizeLite(el){
		return {
			wb:el.offsetWidth||0,
			hb:el.offsetHeight||0
		};
}


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');

      jQuery(div).css({position:"absolute", background:"#e51e00",padding:5,color:"white","margin-top":-20,"margin-left":5 }).text("BON");

      // 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 + 'px';
      div.style.top = point.y + '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;
    }
  };


  jQuery("#mapimage #map").css("left",800).show();  
  var ll = new google.maps.LatLng(55.740665,37.612424);
  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() {
    	jQuery("#mapimage .loading").hide();
    	jQuery("#mapimage #map").css("left",0).show();
    }); 
  var point = new google.maps.LatLng(55.740665,37.612424);
  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_YequRMYC5yamDBTIcDtfIxScwHZ0Qw50cIkRyfxePhQQwroO8xX9xV_fbsCjz10cMpOT3g&callback=loadMap&hl="+lang;  
   script.type = "text/javascript";  
   document.getElementsByTagName("head")[0].appendChild(script);  
}

function checkContactForm() {
  var name = jQuery("#contact-form input[name='contact_name']")[0].value;
  if (name=="Имя")
    name="";  
  var phone = jQuery("#contact-form input[name='contact_phone']")[0].value;
  if (phone=="Телефон")
    phone="";  
  var text = jQuery("#contact-form textarea[name='contact_text']")[0].value;
  if (text=="Ваши пожелания")
    text="";
  jQuery("#contact-form .error").hide();
  if (!name || !phone || !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 (!phone) {
      jQuery(".error",jQuery("#contact-form input[name='contact_phone']").parent()[0]).show();
      jQuery("#contact-form input[name='contact_phone']").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 inviteFormSubmit(e) {
    var pass = jQuery("#invite-password")[0].value;
    jQuery.post("/blog/wp-content/plugins/ryo_catvis/login.php",{ invite_password:pass },function(res) {
      if (res=="OK") {
        location.href='/category/mafia/';
      } else {
        alert("Вы неправильно ввели пароль.");
        jQuery("#invite-password").focus();
      }
    });
    return false;    
}

function pswFocus() {
  if (this.value=="Введите кодовое слово") {
    if (jQuery.browser.msie || jQuery.browser.safari || jQuery.browser.opera) {
      jQuery("#invite-password").unbind("focus").unbind("blur").replaceWith("<input type='password' id='invite-password' value='' name='invite-password'/>");
      jQuery("#invite-password")[0].value='';
      jQuery("#invite-password").focus();
      jQuery("#invite-password").bind("focus",pswFocus).bind("blur",pswBlur);
    }
    else {
      this.value="";
      this.type = "password";
    }    
  }
}

function pswBlur() {
    if (this.value=="") {
      if (jQuery.browser.msie || jQuery.browser.safari || jQuery.browser.opera) {
        jQuery("#invite-password").replaceWith("<input type='text' name='invite-password' id='invite-password' value='Введите кодовое слово'/>");
        jQuery("#invite-password")[0].value='Введите кодовое слово';
        jQuery("#invite-password").bind("focus",pswFocus).bind("blur",pswBlur);
      } else {
        this.value="Введите кодовое слово";
        this.type = "text";
      }    
     }
  }


function closeGallery() {
	jQuery("#fullimage .loading").stop();
	jQuery("#fullimage").stop().css({ width:2,height:150,"margin-left":-1,"margin-top":-1 }).hide();
	jQuery("#fullimage > img.full").hide();
	jQuery("#next_fullimage").stop().hide();
	jQuery("#prev_fullimage").stop().hide();
	jQuery("#fullimage").stop();
	jQuery("#fullimagedesc").hide();
	jQuery("#mapimage").hide();
	jQuery("#map").hide();
	jQuery("#superevent").hide();
	clearInterval(qqival);
	qqival = null;
	jQuery("#overlay").fadeOut(500);
	return false;
};

function bindGalleryView() {
  jQuery(".filmstrip a").click(function() {
		jQuery("#overlay").css("opacity",0).show().fadeTo(500,0.9);
    var gallery_id = jQuery(this).parent().parent().parent().attr("id");
		var img_index = jQuery(this).parent().parent().children().index(jQuery(this).parent()[0]);
		jQuery("#fullimage > img.full").attr({ gallery_id:gallery_id,"image_index":img_index });
		moveToImage(0);
		jQuery("#fullimage").show();
    return false;
  });
  jQuery("#close_fullimage").click(function() {
    jQuery("#overlay").trigger("click");
    return false;
  });
	jQuery("#prev_fullimage").click(function() { return moveToImage(-1); });
	jQuery("#next_fullimage").click(function() { return moveToImage(+1); });
}

function setImageHeight(w,h) {
	if (w>0 && h>0) {
		var fh = parseInt(h)+40;
		var fw = parseInt(w);
		jQuery("#fullimage .loading").css({
			height:Math.round(fh)+10,
			width:Math.round(fw)-1
		});
		jQuery("#fullimage .loading img").css({ "margin-top":Math.round((fh-1))/2-32 });
		jQuery("#fullimage").css({ height:Math.round(fh)-1,"margin-top":-fh/2 }).animate({ 
			width: fw,
			marginLeft:-fw/2
		}, 500 );
	}
}


function moveToImage(direction) {
	var full_image  = jQuery("#fullimage > img.full")[0];
  var gallery_id = jQuery(full_image).attr("gallery_id");
	var container = jQuery("#"+gallery_id+" .filmstrip")[0];
	if (!container)
	 return;
	var img_index = parseInt(jQuery(full_image).attr("image_index"))+direction;
  jQuery("#image_counter").text((img_index+1)+"/"+jQuery("li",container).length);
	var newimg = jQuery("li:eq("+img_index+") a",container)[0];
	if (!newimg)
	 return;
	var fw = parseInt(jQuery(newimg).attr("rw"));
	var fh = parseInt(jQuery(newimg).attr("rh"));
	var flag = 0;
	if (img_index<=0) {
		jQuery("#prev_fullimage").hide();
		flag++;
	}	else {
		jQuery("#prev_fullimage").show();
	}
 	if (img_index>=jQuery("li",container).length-1) {
		jQuery("#next_fullimage").hide();
		flag++;
	} else {
		jQuery("#next_fullimage").show();
	}
	setImageHeight(fw,fh);

	jQuery("#fullimage .loading").hide();
	jQuery("#fullimage .loading img").hide();
	var ival = setInterval(function() { 
			jQuery("#fullimage .loading").show();
			jQuery("#fullimage .loading img").show();
			jQuery(full_image).hide();
			clearInterval(ival); 
			ival = null; 
		},100);

	jQuery.preload([ jQuery(newimg).attr("href") ], {
		onFinish: function(data) {
			clearInterval(ival);
			ival = null;
			jQuery("#fullimage > .loading").hide(); 
			jQuery(full_image).attr({ "image_index":img_index,"src":data.image }).fadeIn(300);
		}
	})
	return false;
}

function refreshGalPos() {
    var galsize = getSizeLite(jQuery("#gal .galphotos").parent()[0]);
    var selnav = jQuery("#galnav .selected")[0];
    var index = jQuery(selnav).parent().children().index(selnav)+1;
    var selimg = jQuery("#gal .galphotos img:eq("+index+")")[0];
    var selimg_w = parseInt(jQuery(selimg).attr("rw"));
    var selimg_pos = parseInt(jQuery(selimg).css("left"));
    jQuery("#gal .galphotos").css("left",-selimg_pos+(galsize.wb-selimg_w)/2);
}

jQuery(document).ready(function() {
  jQuery("#invite-password").bind("focus",pswFocus).bind("blur",pswBlur);

  bindGalleryView();
  jQuery("#close-form").click(function() {
    jQuery("#overlay").trigger("click");
    return false;
  });
  jQuery(".galleryview .nav .right-arrow").click(function() {
    var view = jQuery(this).parent().parent()[0];
    jQuery(".filmstrip",view).stop();
    var pos = jQuery(".filmstrip",view)[0].scrollLeft+view.offsetWidth;
    jQuery(".filmstrip",view).animate({ "scrollLeft":pos },500);
    return false;
  });
  jQuery(".galleryview .nav .left-arrow").click(function() {
    var view = jQuery(this).parent().parent()[0];
    jQuery(".filmstrip",view).stop();
    var pos = jQuery(".filmstrip",view)[0].scrollLeft-view.offsetWidth;
    jQuery(".filmstrip",view).animate({ "scrollLeft":pos },500);
    return false;
  });
  jQuery("#overlay").click(function() {
    jQuery("#invite-form").hide();
    closeGallery();  
    return false;
  });
	jQuery("#footer_link").click(function() {
	 jQuery("#invite-form").show();
	 jQuery("#overlay").css("opacity",0).show().fadeTo(500,0.9);
//	 jQuery("#invite-password").focus();
	 return false;
  });
  jQuery("#invite-form form").submit(inviteFormSubmit);
  jQuery("#post-invite").click(inviteFormSubmit);
  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_phone']")
    .bind("focus",function() { if (this.value=="Телефон" || this.value=="Telephone") this.value=""; }).bind("blur",function() { if (this.value=="") this.value=(lang=="ru" ? "Телефон" : "Telephone"); });
  jQuery("#contact-form textarea[name='contact_text']")
    .bind("focus",function() { if (this.value=="Ваши пожелания" || this.value=="Your wishes") this.value=""; }).bind("blur",function() { if (this.value=="") this.value=(lang=="ru" ? "Ваши пожелания" : "Your wishes"); });
  jQuery("#close_mapimage").click(function() {
	jQuery("#mapimage .loading").stop();
	jQuery("#mapimage").stop().css({ width:2,height:150,"margin-left":-1,"margin-top":-1 }).hide();
	jQuery("#mapimage #map").hide();
	jQuery("#mapimage").stop();
	jQuery("#overlay").fadeOut(500);
	return false;
  });
  jQuery("#googlemaps-link").click(function() {
		if (jQuery.browser.safari)
      jQuery("#mapimage").css("position","absolute");		
		jQuery("#overlay").css("opacity",0).show().fadeTo(500,0.9);
		
  	if (jQuery.browser.safari)
  	 jQuery("#close_mapimage").css({ marginLeft:300 }).show();
    else
  	 jQuery("#close_mapimage").show().animate({ marginLeft:300},500);
  	
		jQuery("#mapimage").show();
   	jQuery("#mapimage .loading").css({ "z-index":10,position:"absolute",left:0 }).show();
   	jQuery("#mapimage .loading img").show();
		jQuery("#mapimage .loading").css({
			height:420,
			width:630
		});
		jQuery("#mapimage .loading img").css({ "margin-top":210-32 });
		jQuery("#mapimage").css({ height:420,"margin-top":-210 }).animate({ 
			width: 600,
			marginLeft:-300
		}, 500 );

    if (!isAPILoaded) {
      initLoader();
    } else 
      loadMap();
    return false;
  });
  if (jQuery("#superevent")[0]) {
		jQuery("#overlay").css("opacity",0).show().fadeTo(500,0.9);
		jQuery("#superevent").show();
  	qqival = setInterval(function() {
        jQuery("#overlay").trigger("click"); 
  		},1000*15);
		jQuery("#superevent .skip").click(function() {
		  jQuery("#overlay").trigger("click");
		  return false;
    });
  }
  if (jQuery("#gal")[0]) {
    bindKeys();
    refreshGalPos();
    jQuery(window).resize(refreshGalPos);
      
    jQuery("#gal .galphotos img").click(function() {
      var el = jQuery("#galnav .selected").next()[0];
      if (!el)
        el = jQuery("#galnav .pic-bullet:first")[0];
      if (el)
        jQuery(el).trigger("click");
    }).hover(function() {
      if (ival2) {
  			clearInterval(ival2); 
  			ival2 = null;
      } 
 			jQuery("#gal .arrows div").stop(true,true).fadeIn(300);
    },function() {
      if (ival2) {
  			clearInterval(ival2); 
  			ival2 = null;
      } 
    	ival2 = setInterval(function() { 
    			jQuery("#gal .arrows div").stop(true,true).fadeOut(300);
    			clearInterval(ival2); 
    			ival2 = null; 
    		},500);
    });
    jQuery("#gal .arrows div").hover(function() {
    			clearInterval(ival2); 
    			ival2 = null; 
    },function() {
    			clearInterval(ival2); 
    			ival2 = null; 
        	ival2 = setInterval(function() { 
        			jQuery("#gal .arrows div").stop(true,true).fadeOut(300);
        			clearInterval(ival2); 
        			ival2 = null; 
        		},500);
    });
    if (jQuery.browser.msie && jQuery.browser.version<7) {
      jQuery("#galnav .pic-bullet").hover(function() {
        jQuery(this).addClass("jsover");
      },function() {
        jQuery(this).removeClass("jsover");
      });
    }
    jQuery("#galnav .pic-bullet").click(function() {
      if (jQuery(this).is(".selected"))
        return false;
      jQuery("#galnav .selected").removeClass("selected");
      jQuery(this).addClass("selected");
      var index = jQuery(this).parent().children().index(this)+1;
      var img = jQuery("#gal .galphotos img:eq("+index+")")[0];
      if (img) {
        var galsize = getSizeLite(jQuery("#gal .galphotos").parent()[0]);
        var w = parseInt(jQuery(img).attr("rw"));
        var pos = parseInt(jQuery(img).css("left"));
        var txt = jQuery(img).attr("alt");
        jQuery("#galimagedesc").text(txt);
        jQuery("#gal .galphotos").animate({ "left":-pos+(galsize.wb-w)/2 },500);
      }   
      return false;
    });
    jQuery("#gal .arrows .left").click(function() {
      var el = jQuery("#galnav .selected").prev()[0];
      if (!el)
        el = jQuery("#galnav .pic-bullet:last")[0];
      if (el)
        jQuery(el).trigger("click");
    })
    jQuery("#gal .arrows .right").click(function() {
      var el = jQuery("#galnav .selected").next()[0];
      if (!el)
        el = jQuery("#galnav .pic-bullet:first")[0];
      if (el)
        jQuery(el).trigger("click");
    });
  }
  jQuery("#sidebar .page-item-618 > a,#sidebar .page-item-624 > a").click(function(e) {
    e.stopPropagation();
    jQuery(this).parent().find(">ul:first").slideToggle(300);
    return false;
  });
});
