$(function($){
    

    $.fn.jpopup = function(options){
	var settings = $.extend({},$.fn.jpopup.defaults,options);
	
	return this.each(function(){ 
	    new jpopup(this,settings);
	});
    }

    var jpopup = function(content,settings){
	this.settings = settings;
	this.content = $(content);
	
	this.elem = $('<div class="jpopup_content"></div>');
	this.backgroundElem = $('<div class="jpopup_bg"></div>');
	this.popupClose = $('<div class="jpopup_close"></div>');
	
	if(this.settings.load){
	    THIS = this;
	    content = "loading...";
	    $.get(this.settings.load, null, function(data,status){
		THIS.content.html(data);
	    });

	}

	this.elem.append(this.popupClose);
	this.elem.append(this.content);
	this.popupStatus = 0;

	$(document.body).append(this.backgroundElem);
	$(document.body).append(this.elem);

	this.setupPopup();
	this.centerPopup();
	this.loadPopup();

	var THIS = this;
	this.popupClose.click(function(){
	   THIS.disablePopup();
	});
	this.backgroundElem.click(function(){
	   THIS.disablePopup();
	});
	$(document).keypress(function(e){
	   if(e.keyCode == 27 && THIS.popupStatus == 1){
	       THIS.disablePopup();
	   }
	});
	return this;
    }
	jpopup.prototype.setupPopup = function(){
	    
	    this.elem.css({
		"width":this.settings.width,
		"height":this.settings.height
	    });
	}

	jpopup.prototype.centerPopup = function(){
	    var windowWidth = document.documentElement.clientWidth;
	    var windowHeight = document.documentElement.clientHeight;
	    var popupHeight = this.elem.height();
	    var popupWidth = this.elem.width();

	    this.elem.css({
		"top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2
	    });
	    //only need force for IE6
	    this.backgroundElem.css({
		"height": windowHeight+100,
		"width":windowWidth
	    });


	}

	jpopup.prototype.loadPopup = function() {
	    if(this.popupStatus == 0){
		this.backgroundElem.css({
		    "opacity": "0.7"
		});
		this.backgroundElem.fadeIn(this.settings.speed);
		this.elem.fadeIn(this.settings.speed);
		this.popupStatus = 1;
	    }
	}

	jpopup.prototype.disablePopup = function() {
	    if(this.popupStatus == 1){
		this.backgroundElem.fadeOut(this.settings.speed);
		this.elem.fadeOut(this.settings.speed);
		popupStatus = 0;
	    }
	}
	

    $.fn.jpopup.defaults = {
	width:"500px",
	height:"300px",
	speed:"slow"

    }
    var _cookie_name = "blacksmith_popup_status_6";
    if(!$.cookie(_cookie_name)){
	$.cookie(_cookie_name,'false',{expires: 120});
    }

    if($.cookie(_cookie_name)=='false'){
	$('<div>p</div>').jpopup({speed:1000,load:"/popup.html"});
	$.cookie(_cookie_name,'true',{expires: 120});
    }else{
	$.cookie(_cookie_name,'true',{expires: 120});
    }
});

