var wp_host = document.location.protocol;
document.write('<script type="text/javascript" src="'+wp_host+'//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>');

var objWP = new jsClassWP();

function jsClassWP(){

  /** инициализация класса WP **/
  this.Init = function(sid,params){
  	var copyright = '\n---------------------------\nwww.web-passport.org';  
    if(sid.length != 32) {alert('Ошибка!\nSID сайта указан не верно'+copyright); return;}
    if(!this.is_array(params)) {alert('Ошибка!\nВторая переменная не является массивом'+copyright); return;}
    if(!this.is_array(params['window'])) {alert('Ошибка!\nПеременная window не является массивом'+copyright); return;}
    if(!this.is_array(params['user'])) {alert('Ошибка!\nПеременная user не является массивом'+copyright); return;}
    
    var domObj = 'a[name=wplogin], input[name=wplogin], img[name=wplogin], a[name=wpmobile], input[name=wpmobile], img[name=wpmobile], a[name=wpprofile], input[name=wpprofile], img[name=wpprofile], a[id=wplogin], input[id=wplogin], img[id=wplogin], a[id=wpprofile], input[id=wpprofile], img[id=wpprofile], a[id=wpmobilepay], input[id=wpmobilepay], img[id=wpmobilepay], a[name=wpmobilepay], input[name=wpmobilepay], img[name=wpmobilepay]';
   
    /** присваиваем найденным объектам события **/
    jQueryWP(domObj).css('cursor','pointer');
  	jQueryWP(domObj).click(function(){
  	    var wp_file = objWP.Proverka(this);
  		switch(wp_file){
  			case 'error':
  			 alert('Ошибка передачи значения id или name'+copyright);
  			break;
  			default:
  			  jQueryWP("head").append("<link>");
              var css = jQueryWP("head").children(":last");
               css.attr({
                rel:  "stylesheet",
                type: "text/css",
                href: wp_host+"//www.web-passport.org/winpop/"+params['window']['version']+"/wp_window.css"
               });
  			
	         objWP.wp_show(wp_host+'//www.web-passport.org/'+wp_file+'.html?site_sid='+sid+'&'+jQueryWP.param(params['window'])+'&'+jQueryWP.param(params['user'])+'&wp_host='+wp_host+'&width=500&height=400');
	        break;
  		}
  		return false;
  	});
  }
  
  
  this.wp_show = function(url){

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			jQueryWP("body","html").css({height: "100%", width: "100%"});
			jQueryWP("html").css("overflow","hidden");
			if (document.getElementById("WP_HideSelect") === null) {//iframe to hide select elements in ie6
				jQueryWP("body").append("<iframe id='WP_HideSelect'></iframe><div id='WP_overlay'></div><div id='WP_window'></div>");
			}
		}else{//all others
			if(document.getElementById("WP_overlay") === null){
				jQueryWP("body").append("<div id='WP_overlay'></div><div id='WP_window'></div>");
			}
		}
		
		if(this.wp_detectMacXFF()){
			jQueryWP("#WP_overlay").addClass("WP_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			jQueryWP("#WP_overlay").addClass("WP_overlayBG");//use background and opacity
		}
		
		var queryString = url.replace(/^[^\?]+\??/,'');
	    var params = this.parseQuery(queryString);
		
		jQueryWP("body").append("<div id='WP_load'><img src='"+wp_host+"'//www.web-passport.org/template/images/loadingprogres.gif' /></div>");
		jQueryWP('#WP_load').show();
			

			TB_WIDTH = (params['width']*1) + 30 || 430;
			TB_HEIGHT = (params['height']*1) + 40 || 330;
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			
			urlNoQuery = url.split('WP_');
			jQueryWP("#WP_iframeContent").remove();
					
			jQueryWP("#WP_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='WP_iframeContent' name='WP_iframeContent"+Math.round(Math.random()*1000)+"' onload='objWP.wp_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' ></iframe><div id='WP_stripe'></div><div id='WP_klz'></div>");
					
			jQueryWP("#WP_klz").click(this.wp_remove);
				
			this.wp_position();
			if(jQueryWP.browser.safari){//safari needs help because it will not fire iframe onload
			   jQueryWP("#WP_load").remove();
			   jQueryWP("#WP_window").css({display:"block"});
			}
		
		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					this.wp_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
  } 
  
  
  /** проверка имени файла **/
  this.Proverka = function(domObj){
  	var wpfiles = ['wplogin','wpmobile','wpprofile','wpmobilepay'];
  	if(jQueryWP.inArray(domObj.name, wpfiles) > -1){return domObj.name;}
  	if(jQueryWP.inArray(domObj.id, wpfiles) > -1){return domObj.id;}
  	return 'error';
  }

  
  /** helper functions below **/
  this.wp_showIframe = function (){
	jQueryWP("#WP_load").remove();
	jQueryWP("#WP_window").css({display:"block"});
  }

  this.wp_remove = function() {
 	jQueryWP("#WP_imageOff").unbind("click");
	jQueryWP("#WP_klz").unbind("click");
	jQueryWP("#WP_window").fadeOut("fast",function(){jQueryWP('#WP_window,#WP_overlay,#WP_HideSelect').trigger("unload").unbind().remove();});
	jQueryWP("#WP_load").remove();
	if(typeof document.body.style.maxHeight == "undefined"){//if IE 6
		jQueryWP("body","html").css({height: "auto", width: "auto"});
		jQueryWP("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
  }

  this.wp_position = function() {
    jQueryWP("#WP_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if(!(jQueryWP.browser.msie && jQueryWP.browser.version < 7)) { // take away IE6
		jQueryWP("#WP_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
  }  

  this.wp_detectMacXFF = function() {
    var userAgent = navigator.userAgent.toLowerCase();
    if(userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1){
      return true;
    }
  }
  
  /** парсинг GET **/
  this.parseQuery = function(query){
   var Params = {};
   if(!query) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for(var i = 0; i < Pairs.length; i++){
      var KeyVal = Pairs[i].split('=');
      if(!KeyVal || KeyVal.length != 2){continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
  }
   
  /** определение массива **/
  this.is_array = function(mixed_var){var key = ''; if(!mixed_var){return false;}if(typeof mixed_var === 'object'){if(mixed_var.hasOwnProperty){for(key in mixed_var){if(false === mixed_var.hasOwnProperty(key)){return false;}}} return true;} return false;}
	
} //End ClassWP
