Type.registerNamespace("PJB.UI.JobSeekers.Controls");

PJB.UI.JobSeekers.Controls.AjaxIPPopup = function() {
    PJB.UI.JobSeekers.Controls.AjaxIPPopup.initializeBase(this);
    this._ipAddress = "";
    this._popupContainer = null;
    this._popupFrame = null;
    this._blockContainer = null;
    this._blockFrame = null;
    this._btnMoreInfo = null;
    this._btnEligible = null;
    this._btnNonUkJob = null;
}
PJB.UI.JobSeekers.Controls.AjaxIPPopup.prototype = {
	initialize: function() {
        PJB.UI.JobSeekers.Controls.AjaxIPPopup.callBaseMethod(this, "initialize");
		// Force display of popup depending on query string parameter.
		if (location.search.toLowerCase().indexOf("ippopup=force") != -1) {
			this._initializePopup();
			return;
		}
		// If cookie is present, don't show popup.
		if (document.cookie.toUpperCase().indexOf("PJBIPPOPUP") != -1) {
			return;
		}
		// Display popup depending on IP address.
		this._checkIP();
    },

    //function to create and show the popup
    _initializePopup: function() {
		// Create a div to contain the iframe.
		// This required so that the iframe does not inherit the opacity set on the block container.
	    this._popupContainer = document.createElement("div");
	    this._popupContainer.id = "ajaxippopup";
	    jQuery(this._popupContainer).css({
			"display": "none",
			"position": "absolute",
			"left": 0,
			"top": 0,
			"width": 716,
			"height": 386,
			"padding": 0,
			"margin": 0,
			"border": "none",
			"z-index": 99999
	    });
	    // Insert popup container as first child document body
	    document.body.insertBefore(this._popupContainer, document.body.firstChild);
		// Create iframe to display popup content.
        this._popupFrame = document.createElement("iframe");
        this._popupFrame.src = "/External/AjaxIPPopup.html";
        this._popupFrame.frameBorder = 0;
        this._popupFrame.frameMargin = 0;
        this._popupFrame.scrolling = "no";
		this._popupFrame.tabIndex = 1;
        this._popupFrame.style.width = "100%";
        this._popupFrame.style.height = "100%";
        $addHandlers(this._popupFrame, {
			"load": this._onFrameLoad
        }, this);
        this._popupContainer.appendChild(this._popupFrame);
        
		// Create container to block mouse events on page.
		this._blockContainer = document.createElement("div");
		jQuery(this._blockContainer).css({
			"display": "none",
			"position": "absolute",
			"left": 0,
			"top": 0,
			"width": "100%",
			"height": "100%",
			"z-index": 99998,
			"background-color": "gray",
			"opacity": 0.5
		});
		$addHandlers(this._blockContainer, {
			"dblclick": this._blockEvent,
			"click": this._blockEvent,
			"mousedown": this._blockEvent,
			"mousemove": this._blockEvent,
			"mouseup": this._blockEvent
		}, this);
	    // Insert block container before popup container
		document.body.insertBefore(this._blockContainer, document.body.firstChild);
		// Create iframe to fix select element bleed through bug in IE6.
        if (Sys.Browser.agent === Sys.Browser.InternetExplorer && Sys.Browser.version < 7) {
			this._blockFrame = document.createElement("iframe");
			this._blockFrame.src = "javascript:" + "\"" + "<html><body style='background-color:gray;'></body></html>" + "\"";
			this._blockFrame.frameBorder = 0;
			this._blockFrame.frameMargin = 0;
			this._blockFrame.scrolling = "no";
			this._blockFrame.tabIndex = -1;
			this._blockFrame.style.width = "100%";
			this._blockFrame.style.height = "100%";
			this._blockContainer.appendChild(this._blockFrame);
		}
        
        this._showPopup();
	},

	_blockEvent: function(ev){
		ev.stopPropagation();
		ev.preventDefault();
	},
	
	_onFrameLoad: function(ev){
		// $addHandler does not support frames, due to bug in event object creation.
		// http://forums.asp.net/t/1037669.aspx
		this._btnMoreInfo = $get("moreBtn", this._popupFrame.contentWindow.document);
		this._btnMoreInfo.onclick = Function.createDelegate(this, this._onMoreInfoButtonClick);
		this._btnEligible = $get("closeBtn", this._popupFrame.contentWindow.document);
		this._btnEligible.onclick = Function.createDelegate(this, this._onEligibleButtonClick);
		this._btnNonUkJob = $get("nonUKBtn", this._popupFrame.contentWindow.document); 
		if(this._btnNonUkJob!=null)
		{
		    // Simulate "I am eligible" click and moreinfo click
		    this._btnNonUkJob.onclick = Function.createDelegate(this, this._onNonUkJobClick);
		} 
		
	},
	_onMoreInfoButtonClick: function(ev){
		// Set session cookie on "Tell Me More" click
        this._setCookie();
    	// Navigate to href
    },

    _onNonUkJobClick: function (ev) {
        // Set permanent cookie on "I am eligible" click
        this._setCookie(true);
        // Navigate to href
    },

	_onEligibleButtonClick: function(ev){
		this._hidePopup();
        // Set permanent cookie on "I am eligible" click
        this._setCookie(true);
        // Track button clicks
    	this._callWebTrends("Eligible.aspx", "EligibleButton");    	
    	// Do not navigate to href
		return false;
	},

    _onWindowResize: function(ev) {
		this._positionPopup();
    },
    
    _positionPopup: function() {
		var jWin = jQuery(window);
		var jDoc = jQuery(document);
		var jPop = jQuery(this._popupContainer);
		var jBlock = jQuery(this._blockContainer);
		
		// get viewport width and height
		// http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
		// TK: jQuery bug? $(window).height() returns document height in Opera!
		var vw = window.innerWidth ? window.innerWidth : jWin.width();
		var vh = window.innerWidth ? window.innerHeight : jWin.height();
		// get document width and height		
		var dw = jDoc.width();
		var dh = jDoc.height();

		// height of block container div
		var bh = Math.max(vh, dh);
        jBlock.css({
			"width": "100%",
			"height": bh
        });
        		
		// get popup width and height
		var pw = jPop.width();
		var ph = jPop.height();

		// get window scroll offsets
		var wscrleft = jWin.scrollLeft();
		var wscrtop = jWin.scrollTop();

		// get centered position of popup
		var pleft = Math.floor((vw - pw) / 2) + wscrleft;
		var ptop = Math.floor((vh - ph) / 2) + wscrtop;
		jPop.css({
			"position": "absolute",
			"z-index": 99999,
			"left": pleft,
			"top": ptop
		});
    },

	_showPopup: function() {
		var jPop = jQuery(this._popupContainer);
		var jBlock = jQuery(this._blockContainer);
		// Need to make popup "visible" to browser in order to get its dimensions.
		jPop.show();
		this._positionPopup();
		// Fade in popup
		jPop.hide();
		jBlock.hide();
		jPop.fadeIn("fast");
		jBlock.fadeIn("fast");
		// Track window resizing and scrolling
		$addHandlers(window, {
			"resize": this._onWindowResize,
			"scroll": this._onWindowResize
		}, this);
    	// Track impression
        this._callWebTrends("InternationalEntry.aspx", "InternationalEntry");
	},
	
	_hidePopup: function() {
		var jPop = jQuery(this._popupContainer);
		var jBlock = jQuery(this._blockContainer);
		// Fade out popup
		jPop.fadeOut("fast");
		jBlock.fadeOut("fast");
	},
	
   // Sets a permanent or session cookie depending on whether a date is supplied.
   _setCookie: function(perm) {
        var	argv = this._setCookie.arguments;	 
        var	argc = this._setCookie.arguments.length;
        var	expires	= null;
        if (perm) {
			var expDays = 90;
			expires = new Date(); 
			expires.setTime(expires.getTime() + (expDays*24*60*60*1000));
		}
        document.cookie	= "PJBIPPOPUP=" +	
			((expires == null) ? ""	: ("; expires="	+ expires.toGMTString())) + "; path=/";
    },
    
    _callWebTrends: function(virtualURL, wtCategory) {
	    if (typeof (dcsMultiTrack) === "function") {
			// Clear out custom properties
			DCSext = {};
			//Clear out multitrack parameters to prevent double counting
            dcsMultiTrack('DCS.dcsuri',virtualURL,'WT.ti',wtCategory
                                                 ,'WT.mc_id',''
                                                 ,'WT.srch',''
                                                 ,'WT.mc_ev',''
                                                 ,'WT.si_cs',''
                                                 ,'WT.pi',''
                                                 ,'WT.oss',''
                                                 ,'WT.oss_r',''
                                                 ,'WT.rv',''
                                                 ,'WT.cg_n',''
                                                 ,'WT.cg_s',''
                                                 ,'WT.si_n',''
                                                 ,'WT.si_p',''
                                                 ,'WT.si_x',''
                                                 ,'WT.seg_1',''
                                                 ,'WT.i_Optimost',''
                                                 )
        } else {
			// WebTrends scripts are not available yet, so delay until document is ready.
			$addHandler(window, "load", Function.createDelegate(this, function () {
				this._callWebTrends(virtualURL, wtCategory);
			}));
        }
    },
    
	_checkIP: function() {
		try {
			typeof PJB.WhiteLabel.UI.JobSeekers.WebServices.PopupListService.PopupListService;
		} catch (err) {
			// On error drop seesion cookie so we don't try again in session
			this._setCookie();
			return;
		}
		// Invoke the web service
		if (this.get_IPAddress()) {
			PJB.WhiteLabel.UI.JobSeekers.WebServices.PopupListService.PopupListService.DisplayPopup(
				this.get_IPAddress(),
				Function.createDelegate(this, this._onSuccess),
				Function.createDelegate(this, this._onFailed),
				null);
		}
	},
	_onSuccess: function(result, userContext, methodName) {		
		// If webservice has returned a value of 'true' so we should show the popup
		// otherwise we drop a permanent cookie so we never check again
		if (result) {
			this._initializePopup();
		} else {
			this._setCookie(true);
		}
	},
	_onFailed: function(error, userContext, methodName) {
		// webservice failed - drop session cookie so we don't try again this session
		this._setCookie();
	},
    
	// Add here any properties passed in from server-side code.
	get_IPAddress: function() {
        return this._ipAddress;
    },
    set_IPAddress: function(val) {
		this._ipAddress = val;
	},
	
    dispose: function() {
        PJB.UI.JobSeekers.Controls.AjaxIPPopup.callBaseMethod(this, "dispose");
    }
}
PJB.UI.JobSeekers.Controls.AjaxIPPopup.registerClass("PJB.UI.JobSeekers.Controls.AjaxIPPopup", Sys.Component);

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
