var is_iphone =false;

var config = {
play:{opacity:0},
    clip: { 
        autoPlay: true
    } ,
plugins:{	
	controls: { 
             	url: '/video/flowplayer.controls-3.1.5.swf',
                height:30,
                scrubberHeightRatio:0.5,
                scrubberBarHeightRatio:0.15,
                sliderColor: '#999999',
                bufferColor: '#333333',
                progressColor: '#333333',
                progressGradient: 'none',
                backgroundGradient: 'none', 
                backgroundColor: '#ffffff', 
                buttonColor:'#014ab5',
                buttonOverColor:'#014ab5',
                tooltipColor:'#1a1a1a',
                tooltipTextColor:'#ffffff',
                scrubber:true, 
                stop:false, 
                playlist:false, 
                fullscreen:false,
                volume:false, 
		play:true,
                mute:true, 
                time:false,  
                tooltips: {
                  buttons: false
                }
	}
	} 
};


var curImgID = 0;
var isAPILoaded = false;


function setImageHeight(w,h,txt) {
	if (w>0 && h>0) {
	//	var fh = 345*parseInt(h)/parseInt(w);
		var fh = parseInt(h)+25;
		var fw = parseInt(w);
		$("#fullimage .loading").css({
			height:Math.round(fh)+10,
			width:Math.round(fw)-1
		});
		$("#fullimage .loading img").css({ "margin-top":Math.round((fh-1))/2-32 });
		$("#fullimage").css({ height:Math.round(fh)-1,"margin-top":-fh/2 }).animate({ 
			width: fw,
			marginLeft:-fw/2
		}, { duration:500,queue:true,
    complete:function() {

			$("#fullimagedesc").text(txt).show();
			var hb = $("#fullimagedesc").height();
      $("#fullimage").animate({ 
            height:Math.round(fh)+5+hb-1,"margin-top":-(fh+hb)/2
       		}, { queue:true,duration:500 });
    
    } });
	}
}

function makeGalleryImage(container,j) {
	j.each(function() {
	 var link = this;
	  $(this).hover(function() {
	   $("span",this).addClass("jsover");
    },function() {
	   $("span",this).removeClass("jsover");
    });
		$(link).click(function() {
			$("#overlay").css("opacity",0).show().fadeTo(500,0.9);
			//var row_index = $(".row",container).index($(this).parent().parent()[0]);
			var img_index = $("a",container).index(link);
			$("#fullimage > img.full").attr({ gallery_id:$(container).attr("gallery_id"),"image_index":img_index });
			moveToImage(0);
			$("#fullimage").show();
			return false;        
		});
	});
}

function getSize(e)
	{
		var w = jQuery.css(e,'width');
		var h = jQuery.css(e,'height');
		var wb = 0;
		var hb = 0;
		var es = e.style;
		if (jQuery(e).css('display') != 'none') {
			wb = e.offsetWidth;
			hb = e.offsetHeight;
		} else {
			var oldVisibility = es.visibility;
			var oldPosition = es.position;
			es.visibility = 'hidden';
			es.display = 'block';
			es.position = 'absolute';
			wb = e.offsetWidth;
			hb = e.offsetHeight;
			es.display = 'none';
			es.position = oldPosition;
			es.visibility = oldVisibility;
		}
		return {w:w, h:h, wb:wb, hb:hb};
	}


function moveToImage(direction) {
	var full_image  = $("#fullimage > img.full")[0];
  var gallery_id = $(full_image).attr("gallery_id");
	var container = $(".gallery[gallery_id="+gallery_id+"]")[0];
	if (!container)
	 return;
  $("#fullimagedesc").hide();
	var img_index = parseInt($(full_image).attr("image_index"))+direction;
	$("#img_counter").text((img_index+1)+"/"+$(">a",container).length);
//	var row_index = parseInt($(full_image).attr("row_index"));
	var newimg = $("a:eq("+img_index+") img",container)[0];
//	alert(newimg);
	if (!newimg) {
	 newimg = $("a:eq("+img_index+") div",container)[0];
  }
	if (!newimg)
	 return;
	var fw = parseInt($(newimg).attr("rw"));
	var fh = parseInt($(newimg).attr("rh"));
	var flag = 0;
	if (img_index<=0) {
		$("#prev_fullimage").hide();
		flag++;
	}	else {
		$("#prev_fullimage").show();
	}
 	if (img_index>=$("a",container).length-1) {
		$("#next_fullimage").hide();
		flag++;
	} else {
		$("#next_fullimage").show();
	}
	if (flag>0)
		$("#gal_nav .red-delimiter").hide();
	else
		$("#gal_nav .red-delimiter").show();

/*	var img_id = $(newimg).attr("image_id");
	if (img_id)
		$("#fullimage").attr({ "image_id":img_id });*/
  var txt = $(".title",$(newimg).parent()[0]).text();
  var fh = $(newimg).attr("rh");
  var fw = $(newimg).attr("rw"); 
	setImageHeight(fw,fh,txt);

	$("#fullimage .loading").hide();
	$("#fullimage .loading img").hide();
	var ival = setInterval(function() { 
			$("#fullimage .loading").show();
			$("#fullimage .loading img").show();
			$(full_image).hide();
			clearInterval(ival); 
			ival = null; 
		},100);
	$.preload([ $(newimg).parent().attr("href") ], {
		onFinish: function(data) {
			clearInterval(ival);
			ival = null;
			$("#fullimage > .loading").hide(); 
			$(full_image).attr({ "image_index":img_index,"src":data.image }).fadeIn(300);
		}
	})
	return false;
}

function closeGallery() {
  $("#login-form").hide();
	$("#overlay").fadeOut(500);
 	$("#fullimage .loading").stop();
	$("#fullimage").stop().css({ width:2,height:150,"margin-left":-1,"margin-top":-1 }).hide();
	$("#fullimage > img.full").hide();
	$("#next_fullimage").stop().hide();
	$("#prev_fullimage").stop().hide();
	$("#fullimage").stop();
	$("#fullimagedesc").hide();
	return false;
};

function prolog() {
	if ($(".gallery")[0]) {
		$(".gallery").each(function() {
			makeGalleryImage(this,$("a",this));
		});
		$("#prev_fullimage").click(function() { return moveToImage(-1); });
		$("#next_fullimage").click(function() { return moveToImage(+1); });
	}
	$("#close_fullimage").click(closeGallery);
	$("#overlay").click(closeGallery);
}

function pswFocus() {
  if (this.value=="Пароль") {
    if ($.browser.msie || $.browser.safari || $.browser.opera) {
      $("#login-form input[name='password']").replaceWith("<input type='password' name='password' value=''/>");
      $("#login-form input[name='password']")[0].value='';
      $("#login-form input[name='password']").focus();
      $("#login-form input[name='password']").bind("focus",pswFocus).bind("blur",pswBlur);
    }
    else {
      this.value="";
      this.type = "password";
    }    
  }
}

function pswBlur() {
    if (this.value=="") {
      if ($.browser.msie || $.browser.safari || $.browser.opera) {
        $("#login-form input[name='password']").replaceWith("<input type='text' name='password' value='Пароль'/>");
        $("#login-form input[name='password']")[0].value='Пароль';
        $("#login-form input[name='password']").bind("focus",pswFocus).bind("blur",pswBlur);
      } else {
        this.value="Пароль";
        this.type = "text";
      }    
     }    
  }

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.set_map(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", background:"white",padding:5,color:"#333"}).text("Российский Союз ректоров");

      // Then add the overlay to the DOM
      var panes = this.get_panes();
      panes.overlayLayer.appendChild(div);
    }

    // Position the overlay 
    var point = this.get_projection().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;
    }
  };


  $("#fullimage #map").show();  
// 	$("#fullimage .loading").hide();
  var ll = new google.maps.LatLng(55.702815,37.531786);
  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.702815,37.531786);
  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" });  
}
  
function initLoader() {
   var script = document.createElement("script");  
   script.src = "http://www.google.com/jsapi?key=ABQIAAAA1ZfSf4A_YequRMYC5yamDBSXTzKFCttPO8AtBWDTguhXUE082xSe5f4wE9nKEBixQnKQL4YSHEDjLQ&callback=loadMap&hl=ru";  
   script.type = "text/javascript";  
   document.getElementsByTagName("head")[0].appendChild(script);  
}

function removeTag() {
  $(this).unbind("click");
  $(this).parent().remove();
  updateTags();
  return false;
}

function updateTags() {
  var tags = "";
  $("#work_tags .name").each(function() {
    tags += (tags ? "," : "")+$(this).attr("v");
  })
  $("input[name=category]").val(tags);                                      
}
  
$(document).ready(function() {

    var version = flashembed.getVersion();  
    var supported = flashembed.isSupported([9, 115]);      
    if(!supported){  
      $(".videoclip").append( $("<div/>").addClass("no-flash").html("<div>для просмотра требуется Adobe Flash Player</div>")[0] );
    } else {
      $(".videoclip").empty().flowplayer("/video/flowplayer-3.1.5.swf", config );
    }
	prolog();
/*  $("#press .items .item a").hover(function() {
	   $("span",this).addClass("jsover");
    },function() {
	   $("span",this).removeClass("jsover");
    });*/
  if ($.browser.msie) {    
    $("#register-link,#cancel-link,#save-link,#login-form #login_btn").hover(function() {
      $(this).addClass("link_over");
    },function() {
      $(this).removeClass("link_over");
    });
  }    
    
  $("#close-link").click(closeGallery);
  $("#login-form input[name='login']").bind("focus",function() {
    if (this.value=="Логин") {
      this.value="";    
    }
  }).bind("blur",function() {
    if (this.value=="")
      this.value="Логин";    
  });
  $("#login-form input[name='password']").bind("focus",pswFocus).bind("blur",pswBlur);
  $("#login-link").click(function() {
			$("#overlay").css("opacity",0).show().fadeTo(500,0.9);
			$("#login-form").show();
			$("#login-form input[name='login']").focus();
			return false;
  }); 
  $(".stuff #photos-nav .next").click(function() {
    var sc = parseInt($(".stuff .gallery")[0].scrollLeft);
    $(".stuff .gallery")[0].scrollLeft = sc+100;
    return false;
  }); 
  $(".stuff #photos-nav .prev").click(function() {
    var sc = $(".stuff .gallery")[0].scrollLeft;
    $(".stuff .gallery")[0].scrollLeft = sc-100;
    return false;
  }); 
  $("input[type='file']").filestyle({ 
     image: "/i/attach.jpg",
     imageheight : 25,
     imagewidth : 110,
     width : 310
 });
 if ($("#indexb")[0]) {
  if (is_iphone && $.browser.safari) {

    $("#overlay,#fullimage,#fullimage_close").css("position","absolute");  
      $("#overlay").css({ left:window.pageXOffset,top:window.pageYOffset,height:window.innerHeight });
    window.onscroll = function() {
      $("#overlay").css({ left:window.pageXOffset,top:window.pageYOffset,height:window.innerHeight });
    }
  }

  $("#indexb #indexb_link").click(function() {
		$("#overlay").css("opacity",0).show().fadeTo(500,0.9);
      $("#fullimage").css("position","absolute");		
    fh= 800;
    fw = 589;
		$("#fullimage .loading").css({
			height:Math.round(fh)+10,
			width:Math.round(fw)-1
		});
		$("#fullimage .loading img").css({ "margin-top":Math.round((fh-1))/2-32 });
		$("#fullimage").css({ height:Math.round(fh)-1,"margin-top":-fh/2 }).animate({ 
			width: fw,
			marginLeft:-fw/2
		}, { duration:500,queue:true,
    complete:function() {
			var hb = $("#fullimagedesc").height();
      $("#fullimage").animate({ 
            height:Math.round(fh)+5+hb-1,"margin-top":-(fh+hb)/2
       		}, { queue:true,duration:500 });
    
    } });
		
		
		$("#fullimage").show();
  	$("#fullimage .loading").hide();
  	$("#fullimage .loading img").hide();
  	var full_image  = $("#fullimage > img.full")[0];
  	var 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;

  });
  } else {
  if (is_iphone && $.browser.safari) {

    $("#overlay,#fullimage,#fullimage_close").css("position","absolute");  
      $("#overlay").css({ left:window.pageXOffset,top:window.pageYOffset,height:window.innerHeight });
      $("#fullimage,#fullimage_close").css({ left:window.pageXOffset+window.innerWidth/2,top:window.pageYOffset+window.innerHeight/2 });
    window.onscroll = function() {
      $("#overlay").css({ left:window.pageXOffset,top:window.pageYOffset,height:window.innerHeight });
      $("#fullimage,#fullimage_close").css({ left:window.pageXOffset+window.innerWidth/2,top:window.pageYOffset+window.innerHeight/2 });
    }
  }

  }
  $(".contacts .map-link").click(function() {
		if ($.browser.safari)
      $("#fullimage").css("position","absolute");		
		$("#overlay").css("opacity",0).show().fadeTo(500,0.9);
		$("#fullimage").show();
   	$("#fullimage .loading").show();
   	$("#fullimage .loading img").show();
		setImageHeight(600,375,"");
    if (!isAPILoaded) {
      initLoader();
    } else 
      loadMap();
    return false;
  });
  $("#add_tag a").click(function() {
    var select = $(this).parent().find(">select")[0];
    var tag = $(select).val();
    if (!tag || $("#work_tags > div > .name[v="+tag+"]")[0])
      return false;
    var tagElem = $("<div><span class='name' v=''></span><a href='#' class='remove_button'></a><br clear='left'/></div")[0];
    $(">.name",tagElem).attr("v",tag);
    $(">.name",tagElem).text($(">option[value="+tag+"]",select).text());
    $(">.remove_button",tagElem).click(removeTag);
    $(select).val("");
    $("#work_tags").append(tagElem);
    updateTags(); 
    return false; 
  });
  $("#work_tags .remove_button").click(removeTag);
  $("#save-link").click(function() {
    $("#add_tag a").trigger("click");
    return true;
  });
  
  $("#indexb .info .pics").cycle({
    delay:  2000, 
    speed:  500,
    fx: 'custom', 
    cssBefore: { left: 200 }, 
    animIn:  { left: 0 }, 
    animOut: { left: -200 },
    before:function() {
      var cont = $("#"+$(this).attr("id").replace("img_","info_"))[0];
      $("#indexb .cur_info").html($(cont).html());      
    } 
  });
});
			
