﻿/*
*   Needs: blockUI_v2.31.js, htmlparser.js, UFrame_FAP3.0.js, modalDialog.css, modalDialog_IE6.css
*
*   Example of usage:  
*   showModalDialog("testUFrameForm.aspx?edid=00&salerent=0&agentid=30472");
*   or
*   showCustomModalDialog(<any text or html>);
*
*   Note that the htmlparser.js doesn't pick up conditional style sheets of the form: <!--[if IE]> etc.
*/

var slowResponseLoadingModal_Width = 300; 
var slowResponseLoadingModal_Height = 212,  animationSpeed = 600, showAnimation = false, loadingAnimationStartTime, dialogCheck;
var h;
var wh;
var modalContentReady = false;
var modalDivRef;
var loadingDivRef;
var mainFormName = null;
var modalVisible = false;


function showModalCover(onBlockCallback) {

    $(document).bind('keydown.modal', keyUp);
    var width = 'auto';
    if ($.browser.opera) { width =  '100%'; }
    if ($.browser.msie) {
        if ($.browser.version == '6.0') { //ie6 hack
            width = '1px';
        } else {
            width = null;
        }
     }
    

    $.blockUI({ message: $('#modalDialog'), showOverlay: true, fadeIn: 700, onBlock: onBlockCallback, focusInput: true, centerY: false, centerX: true,
    css: {marginLeft:-(slowResponseLoadingModal_Width/2),width:width,'float':'left',
    cursor: 'default', backgroundColor: 'transparent', border: 'none', 'position':'absolute' },
        overlayCSS: { backgroundColor: '#333333', opacity: 0.5, cursor: 'default' }
    });


}

function keyUp(e) {
    keycode = e.which || e.keyCode;
    if (keycode == 27) {closeModalDialog();$(document).unbind('keydown.modal');}
}
function contentReady() {
    if (modalContentReady) {
        clearTimeout(dialogCheck);
        setModalContent("", false);
        
        $('#UFrame1').removeAttr("style").css({ 'display': 'block', 'visibility': 'visible' });

//        $('#modalDialog').click(function() {
//            $('#UFrame1').stop();
//            $('.modal_n, .modal_s').stop();
//            $('.blockMsg').stop();
//        });
       
        resizeAnimation();

        showAnimation = false;
        $("#modalContent :input:visible:enabled:first").focus();

    }

    else if (loadingAnimationStartTime != null && loadingAnimationStartTime.getTime() < new Date().getTime() - 30000) {
        renderModalCoverExists("Sorry there is a problem and we cannot complete your request at this time.", slowResponseLoadingModal_Height, slowResponseLoadingModal_Width);
        $('#loadingAnimation').css({ 'display': 'none', 'visibility': 'hidden' });
        resizeAnimation();
    }
    else {
        //display loading animation for 2 seconds and then until content ready.
        if (!showAnimation) {
            $('#UFrame1').css({ 'display': 'none', 'visibility': 'hidden' });
            loadingAnimationStartTime = new Date();
            renderModalCoverExists("<img id='waitAnimation' alt='Please wait' src='/content/images-2011/animation/wait.gif' />", slowResponseLoadingModal_Height, slowResponseLoadingModal_Width);
        }
        showAnimation = true;
        dialogCheck = setTimeout(contentReady, 500);
    }
}

function resizeAnimation() {
	var c = $('#UFrame1'), d = $('#modalDialog'), content = $('#modalContent');
	var dims = {
		content: {h: content.height(), w: content.width() },
		dialog: { h: d.height(), w: d.width() },
		margin: { t: 0, l: 0 },
		padding: {
			x: getXPadding(content) + getXPadding('.modal_e') + getXPadding('.modal_w'),
			y: getYPadding(content) + getYPadding('.modal_n') + getYPadding('.modal_s')
		},
		uframe: { delta: { x: 0, y: 0 }, h: c.height(), w: c.width() },
		window: { h: $(window).height(), w: $(window).width(), x: $(window).scrollLeft(), y: $(window).scrollTop() }
	};

	c.width($.browser.msie && ($.browser.version == '6.0') ? 'auto' : '100%');

	if (dims.uframe.w !== c.width()) { // reset widths
		dims.uframe.delta.x = dims.uframe.w - c.width();
		dims.uframe.w -= dims.uframe.delta.x;
		dims.content.w -= dims.uframe.delta.x;
		dims.dialog.w -= dims.uframe.delta.x;
	}
	if ($.browser.msie && ($.browser.version == '7.0')) {
		if ((dims.dialog.w === dims.uframe.w + dims.padding.x) || (dims.uframe.delta.x === 0)) {
			dims.dialog.w = dims.uframe.w + dims.padding.x;
		}
	}
	dims.margin.l = (Math.floor(dims.dialog.w / 2) * -1) + dims.window.x;
	dims.margin.t = Math.max(Math.floor((dims.window.h - dims.dialog.h) / 2), 0) + dims.window.y;

	// IE's JS engine is too slow to animate contents smoothly...
	if ($.browser.msie) { c.css('visibility', 'hidden'); }

	if ($.browser.msie && ($.browser.version == '6.0')) { // no animation for IE6 (aww)
		if (d.height() !== dims.dialog.h) { d.height(dims.dialog.h); }
		d.width(dims.dialog.w);
		$('.modal_n, .modal_s').width(dims.uframe.w);
		$('.blockMsg').css({
			top: 0, left: '50%', marginLeft: dims.margin.l, marginTop: dims.margin.t
		});
		c.height(dims.uframe.h).width(dims.uframe.w).css('visibility', 'visible');
	}
	else {
		c.height(slowResponseLoadingModal_Height).width(slowResponseLoadingModal_Width).animate({
			height: dims.uframe.h, width: dims.uframe.w
		}, animationSpeed);
		d.animate({ height: dims.dialog.h, width: dims.dialog.w }, animationSpeed);
		$('.modal_n, .modal_s').animate({ width: dims.uframe.w }, animationSpeed);
		$('.blockMsg').animate({
			top: 0, left: '50%', marginLeft: dims.margin.l, marginTop: dims.margin.t
		}, animationSpeed, function() { // switch contents back on for IE
			if ($.browser.msie) { c.css('visibility', 'visible'); }
		});
	}
}

//pass in the id of the div whose height you want to use
function resizeVerticalAnimation(divId) {
    var c = $('#UFrame1');
    h = $('#' + divId).height(); 
    wh = $(window).height();
    var x = 5;
    //no animation for ie6
    if ($.browser.msie && $.browser.version == "6.0") {
        c.height(h);
        $('.blockMsg').css('top', ($(window).height() / 2) + 'px');
        if ($('#modalDialog').height() / -2 + $(window).scrollTop() < ($(window).height() / -2)) {
            $('.blockMsg').css('margin-top', 10 - ($(window).height() / 2) + 'px');
        }
        else {
        $('.blockMsg').css('margin-top', ($('#modalDialog').height() / -2) + $(window).scrollTop() + 'px');
    }


    }
    else {
        c.animate({ height: h }, animationSpeed);
        if (h > 212) { // minimum height for modal

            if ((((wh - h) / 2) + $(window).scrollTop()) > 0) {
                x = (((wh - h) / 2) + $(window).scrollTop());
            }
        $('.blockMsg').animate({
            top: '0',
            marginTop: x
        }, animationSpeed); };
    }
}

function resizeVerticalHorizontalAnimation(theWidth, theHeight) {
    var c = $('#UFrame1'), d = $('#modalDialog');
    var h = theHeight, wh = $(window).height(), w = theWidth, ww = $(window).width();

//    //no animation for ie6
    if ($.browser.msie && $.browser.version == "6.0") {
        c.height(h);
        c.width(w);
        $('.modal_n, .modal_s').width(w - 5);
        var marTop = ($('#modalDialog').height() / -2) + $(window).scrollTop();
        if (marTop < 0) {marTop = 5;}
        $('.blockMsg').css('top', ($(window).height() / 2) + 'px').css('left', ($(window).width() / 2) + 'px');
        $('.blockMsg').css('margin-top', marTop + 'px').css('margin-left', ($('#modalDialog').width() / -2) + $(window).scrollLeft() + 'px');
    }
    else {
        d.height(h + 30);
        d.width(w + 30);
        c.animate({ height: h, width: w }, animationSpeed);
        $('.modal_n, .modal_s').width(w);
        if (h > 212) { // minimum height for modal
            $('.blockMsg').animate({
                top: '0',
                marginTop: (((wh - h) / 2) + $(window).scrollTop() - 15),
                left: '0',
                marginLeft: (((ww - w) / 2) + $(window).scrollLeft() - 15)
            }, animationSpeed);
        };
    }
}

function getXPadding(selector) {
	selector = (typeof selector === 'string') ? $(selector) : selector;
    return parseInt(selector.css('padding-right').replace('px', ''), 10) + parseInt(selector.css('padding-left').replace('px', ''), 10);
}
function getYPadding(selector) {
	selector = (typeof selector === 'string') ? $(selector) : selector;
    return parseInt(selector.css('padding-top').replace('px', ''), 10) + parseInt(selector.css('padding-bottom').replace('px', ''), 10);
}

function checkModalState() {
    if (modalVisible) {
        //Not good. A max of one modal dialog should be visible at any one time.
        alert('Error! - Only one modal dialog should be called at a time!');
        return false;
    }
    return true;
}

function showCustomModalDialog(msg) {
    if (!checkModalState()) return;
    prepModalDialog();

    showModalCover();
    $('#modalContent').html(msg);
     setModalDimensions();

    modalVisible = true;
}

function renderModalCoverExists(msg, height, width) {
    setModalContent("<div id='c1' style='height: " + height + "px; width: " + width + "px;'>" + msg + "</div>", true);
    setModalDimensions();
}

function closeModalDialog() {
    cacheTheForm.Reset();
    $.unblockUI();
    loadingAnimationStartTime = null;
    showAnimation = false;
    modalContentReady = false;
    $('#modalDialog').css('display', 'none');
 
    modalVisible = false;
    return false;
}

function setModalDimensions() {

    //todo: do we want scroll bars inside modal?
    //    browserWindowHeight = $(window).height();
    //    if ((browserWindowHeight - 40) < modalContentHeight) {
    //        $('#UFrame1').css('overflow-y', 'scroll');
    //        $('#UFrame1').css('overflow-x', 'hidden');
    //        $('#UFrame1').css('padding-right', '20px');
    //        }
    var c = $('#modalContent');
    modalContentHeight = c.height();
    modalContentWidth = c.width();
    dialogWidth = $('#modalDialog').width();
    $('.modal_n, .modal_s').width(modalContentWidth);
    var h = ($(window).height() - $('#modalDialog').height()) / 2 //- 46;

    // $('.blockMsg').css({ 'top': '50%', left: '50%', marginTop: $(window).scrollTop() + h, marginLeft: Math.floor(dialogWidth / 2) * -1 });
    $('.blockMsg').css({ 'top': '0', left: '50%', marginTop: (h + $(window).scrollTop()), marginLeft: Math.floor(dialogWidth / 2) * -1 });
}

function showModalDialog(src, width) {
    cacheTheForm();
    if (width && !isNaN(parseInt(width, 10))) {
        slowResponseLoadingModal_Width = width;
    }
    if (!checkModalState()) return;
    modalContentReady = false;
    prepModalDialog();
    showModalCover(contentReady);

    $('#UFrame1').css({ 'display': 'none', 'visibility': 'hidden' });
    renderModalCoverExists("<img id='waitAnimation' alt='Please wait' src='/content/images-2011/animation/wait.gif' />", slowResponseLoadingModal_Height, slowResponseLoadingModal_Width);
   
    UFrameManager.init({
        id: "UFrame1",  
        loadFrom: src,
        initialLoad: "GET",
        showProgress: false
        //progressTemplate: "<img id='waitAnimation' alt='Please wait' src='/content/images-2011/animation/wait.gif' />"
    });
    
    modalVisible = true;
}

function navigateModalDialog(src, width) {
//Not quite sure this is the correct method to keep pages within the visible modal
    if (!modalVisible) showModalDialog(src, width);
    
   if (width) {
           slowResponseLoadingModal_Width = width;
       }
   // if (!checkModalState()) return;
    modalContentReady = false;
    
    
   // showModalCover(contentReady);

    $('#UFrame1').css({ 'display': 'none', 'visibility': 'hidden' });
    renderModalCoverExists("<img id='waitAnimation' alt='Please wait' src='/content/images-2011/animation/wait.gif' />", slowResponseLoadingModal_Height, slowResponseLoadingModal_Width);
     UFrameManager.init({
        id: "UFrame1",  
        loadFrom: src,
        initialLoad: "GET",
        showProgress: false,
     
       progressTemplate:""//"<img id='waitAnimation' alt='Please wait' src='/content/images-2011/animation/wait.gif' />"
    });

   dialogCheck = setTimeout(contentReady, 500);

}


function prepModalDialog() {
    if (modalDivRef != null) {
        document.body.removeChild(modalDivRef);
        modalDivRef = null;
        loadingDivRef = null;
    }

    modalDivRef = document.createElement('div');
    modalDivRef.setAttribute('id', 'modalDialog');
    var HTML = "<div id='modal_nw' class='modal_nw'><div id='modal_ne 'class='modal_ne'><div id='modal_n' class='modal_n'></div></div></div>";
    HTML += "<div class='modal_close' onclick='closeModalDialog();'></div>";
    HTML +=  "<div class='modal_w'><div class='modal_e'><div id='modalContent'>";
    HTML +=    "<div class='UFrame' id='UFrame1'></div>";
    HTML +=  "</div></div></div>";
   // HTML += "";
    HTML += "<div class='modal_sw'><div class='modal_se'><div class='modal_s'></div></div></div>";
    
    modalDivRef.innerHTML = HTML;

   
    document.body.appendChild(modalDivRef)
 //   document.getElementById(mainFormName).appendChild(modalDivRef);
    $('#modalDialog').addClass('modalDialog');
}



function setModalContent(content, show) {
    if (loadingDivRef != null && document.getElementById('modalContent') != null) {
        document.getElementById('modalContent').removeChild(loadingDivRef);
        loadingDivRef = null;
    }

    if (show == true) {
        loadingDivRef = document.createElement('div');
        loadingDivRef.setAttribute('id', 'loadingContent');
        var HTML = content;

        loadingDivRef.innerHTML = HTML;
        document.getElementById('modalContent').appendChild(loadingDivRef);
    }
    
}
function cacheTheForm() { cacheTheForm.theForm = window.theForm; }
cacheTheForm.Reset = function () { window.theForm = cacheTheForm.theForm; }

function GetParams(obj) { 

return $(obj).attr('href').split('?')[1]; }

function ShowMultipleContactAgentModal(obj) {
    var pQuery = GetParams(obj);
    trackEvent('_trackEvent', 'Modal', 'Contact Agent', pQuery);
    showModalDialog("/contactAgentModal.aspx?" + pQuery);

    return false;
}

function ShowContactAgentModal() {
	// width: 527

    var pQuery = GetParams(this);	
	trackEvent('_trackEvent', 'Modal', 'Contact Agent', pQuery);
	showModalDialog("/contactAgentModal.aspx?" + pQuery);

    return false;
}
function ShowEmailFriendModal() {
	// width: 872
	var pQuery = GetParams(this);
	trackEvent('_trackEvent', 'Modal', 'Email a Friend', pQuery);
	showModalDialog("/emailFriendModal.aspx?" + pQuery);
	return false;
}

function ShowValuationModal(obj) {
    var pQuery = GetParams(obj);
    trackEvent('_trackEvent', 'Modal', 'Request valuation', pQuery);
    showModalDialog("/requestvaluationmodal.aspx?" + pQuery);
    return false;
}

function autoShowValuationModal(obj) {

    if ($.cookie("npts") == null && $.cookie("notnow") == null) {
        if ($.cookie("pvc") == null || Number($.cookie("pvc").split(",")[0]) < 1) {
            // The server controls whether the html for the modal is output to the source (after the 6 property view)
            // only show if the cookie is 0, i.e if a user views a property and uses the back button the cookie value would have increased to 1
            // cookie is only 0 when the dialog was loaded for the first time.
            var date = new Date();
            date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
            $.cookie("pvc", "1", { expires: date });
     
            ShowValuationModal(obj);
        }
    }
}


/*
function ShowValuationModal(doNotAutoPopUp) {
showModalDialog("/forms/valuationModal.aspx?dnap=" + doNotAutoPopUp);
return false;
}
*/
function ShowLoginModal() {
	var pQuery = GetParams(this);
	trackEvent('_trackEvent', 'Modal', 'Login', pQuery);
	showModalDialog("/loginmodal.aspx?" + pQuery);
	return false;
}

function ShowRegisterModal() {
	var pQuery = GetParams(this);
	trackEvent('_trackEvent', 'Modal', 'Register', pQuery);
	showModalDialog("/registermodal.aspx?" + pQuery);
	return false;
}

function ShowMousePriceModal(obj) {
    var pQuery = GetParams(obj);
    trackEvent('_trackEvent', 'Modal', 'MousePrice', pQuery);
    showModalDialog("/mousepricemodal.aspx?" + pQuery);
    return false;
}

function NavigateToRegisterModal() {
	var pQuery = GetParams(this);
	trackEvent('_trackEvent', 'Modal', 'Modal navigate to register modal', pQuery);
	navigateModalDialog("/registermodal.aspx?" + pQuery);
	return false;
}
function ShowPostcodeModal() {

	showModalDialog('/postcodeLookupModal.aspx', 500);
	return false;
}

function trackEvent(f, name, description, data) {

    var gaType = trackEvent.gaType = trackEvent.gaType || { sync: (typeof pageTracker !== 'undefined'), async: (typeof _gaq !== 'undefined') };

	if (gaType.sync) { pageTracker[f](name, description, data); }
	if (gaType.async) {_gaq.push([f, name, description, data]); }
}

//Stub for email alert
function ShowEmailAlertModal() { }

function ShowMorePlacesModal() { showModalDialog("/myplacesmodal.aspx?" + GetParams(this)); return false; }

function ShowForgottenModal() {return true; }
function NavigateToForgottenModal() { return true; }

function CheckTracker(pQuery, eventType, action) {
   
    if (typeof pageTracker != 'undefined') {
        pageTracker._trackEvent(eventType, action, pQuery); 
     }
    else {
        //script might not have loaded. Defer it to end of script loads.
        $(document).ready(function() {
        if (typeof pageTracker != 'undefined') {
             pageTracker._trackEvent(eventType, action, pQuery); 
            }
        });
    }
}
