var TLPopup = (function () {

// *****************************************************************************************************************
// Mobil popup function
// *****************************************************************************************************************
// TODO : Refactor to object literal to modularize and namespace.
    var POP_DIV_OBJ_ID = 'hiddenPopup_div';
    var POPUP_HEADER = 'hiddenPopup_edit_header';
    var POPUP_CONTENT = 'hiddenPopup_edit_body';


    function setupPopups() {
        // Usage : copy template link into place. Populate the fields as static text in the html page.
        // Motivation : <a href="javascript:void(0)" onclick="showHelpTextLayer('<%=sg.getLable("nameHelpText")%>','<%=sg.getLable("nameHelpHeader")%>','<%=sg.getLable("close")%>')"> <%=sg.getLable("linkNameInfo")%></a>

        //    T E M P L A T E    L I N K  -  dtaPopup
        //    <a class="dtaPopup"
        //        href="<%=pul.getLink("").getLink()%>"
        //        data-popup-title=""
    	//        data-popup-close-href=""
        //        data-popup-window=""
        //        data-popup-unwrapid="article"
        //        data-popup-text=""><%=pul.getMenuLabel()%></a>
        $('.dtaPopup').unbind('click').click(function(e) {
            //    $('.dtaPopup').click(function(e) {
            var link = this.href;
            var title = this.getAttribute('data-popup-title');
            var closeHref = this.getAttribute('data-popup-close-href');
            var unwrapid = this.getAttribute('data-popup-unwrapid');
            var text = this.getAttribute('data-popup-text');            
            var windowData = this.getAttribute('data-popup-window'); // to keep backward compat.
            var close = this.getAttribute('data-popup-close'); // to keep backward compat.
            
            if (TLUtils.isMobileClientJS()) {
            	if(text && text.indexOf("hideHelpDivAtMousePosition") != -1){
            		text = text.replace("hideHelpDivAtMousePosition","TLPopup.hidePopupDiv");
            	}
            	if(close && closeHref){
                	replaceCloseHref(closeHref, close);
                }else{
                	replaceCloseHrefDefault();
                }
            	
                $('#' + POPUP_CONTENT).css('top', e.pageY + "px"); //Move popup beside trigger.
                if (text) { // If we have text given, just display it.
                    triggerPopupWithContent(text, title);
                	if(text.indexOf("seat") != -1){
                		openSeating();
                	}

                } else {
                    triggerPopupWithUrl(link, unwrapid, title);
                }
            } else {
                if (text) {
                	if(text.indexOf("seat") != -1){
                		openSeating();
                	}else{
	                    if (!close) alert('data-popup-close is required when launching legacy popup windows');
	                    showHelpTextLayer(text, title, close);
                	}
                    if(close && closeHref){
                    	replaceCloseHref(closeHref, close);
                    }else{
                    	replaceCloseHrefDefault();
                    }
                    //showWaitMessageShadow(); // Blue Background
                } else {  // If we have text given, just display it.
                    // Externalized : onClick="window.open('/presentation/frameset/info.jsp?type=Editorial&name=DeliveryHelpEticket&ums=1', 'DeliveryHelp', 'status=no,toolbar=no,menubar=no,scrollbar=yes,location=no,width=520,height=450,left=80,top=80')"
                    window.open(link, title, windowData);
                }
            }
            return false;   // Don't follow any hrefs.
        });

        //    T E M P L A T E    L I N K  -  dtaMouseOverInfo
        //    <a class="dtaMouseOverInfo" href="#"
        //         data-popup-title="" data-popup-text="<%=StringUtils.escapeAllQuotes(sgAvail.getLable("labelOWCDescription"))%>"><%=sgAvail.getLable("labelOWCReadMore")%></a>
        if (TLUtils.isMobileClientJS()) {
            $('.dtaMouseOverInfo').unbind('mouseover').click(function(e) {
                var title = this.getAttribute('data-popup-title');
                var text = this.getAttribute('data-popup-text');
                triggerPopupWithContent(text, title);
                return false; // Don't follow any hrefs.
            });
        } else {
            $('.dtaMouseOverInfo').click(function(e) {
                return false;
            });  // Don't follow the # link.
            $('.dtaMouseOverInfo').unbind('mouseover').mouseover(function(e) {
                var message = new Object();
                message.header = this.getAttribute('data-popup-title');
                message.message = this.getAttribute('data-popup-text');
                PageInfoMessages.displayHoverMessage(e, this, message);
                return false; // Don't follow any hrefs.
            });
        }

        // NOTE :  .live binds to document and catches the events as they bubble up, so it's far too late to prevent default actions or anything.
        $('.dtaInternalPopupLink').unbind('click').live('click', function(e) {
            //        $('#iframeDiv').load(this.href, function() {  alert('Load was performed.' + $('#iframeDiv').size()+this.href); }  );
            $('#iframeDiv').load(this.href);
            $('#iframeTitle').html($(this).text());
            return false;
        });
    }

    function retrieveDiv() {
        var helpDivObj = $('#' + POP_DIV_OBJ_ID);
        if (!helpDivObj)
            alert("ERROR : Page is missing required DIV element to enable popup information :" + POP_DIV_OBJ_ID);
        return helpDivObj;
    }

    function showPopupDiv() {
        // create div object (remove it if it exists, offsetHeight for IE in hideSelectBoxesUnderDiv() call reasons...)
        var helpDivObj = retrieveDiv();
        var windowHeight = $(window).height();
        var windowWidth = $(window).width();
        var scrollPosition = $(window).scrollTop();
        // helpDivObj.css("top", 20);
        // helpDivObj.css("left", 20);
        helpDivObj.css("width", (windowWidth - 50));
        this.scroll(0, 0);
        display(POP_DIV_OBJ_ID, true);
    }

    function hidePopupDiv() {
        hideObjAtMousePos(POP_DIV_OBJ_ID);
    }
    
    function replaceCloseHref(href, close){
    	$('#hiddenPopup_readonly').replaceWith("<div id=\'hiddenPopup_readonly\' ><a class=\'button-left light cancel\' href=\'" + href + "\'>" + close + "</a></div>");
    	$('#stickyAnchorCloseX').attr("href", href);

    }
    
    function replaceCloseHrefDefault(){
    	$('#hiddenPopup_readonly').replaceWith("<div id=\'hiddenPopup_readonly\' ><a class=\'button-left light cancel\' href=\'javascript:TLPopup.hidePopupDiv()\'>" + CLOSE + "</a></div>");
    }

    function triggerPopupWithContent(contentText, headerText) {
        if (headerText == undefined) {
            headerText = '';
        }
        if (contentText == undefined) {
            contentText = '';
        }
        retrieveDiv(); // Confirm page has the div.
        $('#' + POPUP_HEADER).html(headerText);
        $('#' + POPUP_CONTENT).html(contentText);
        showPopupDiv();
    }

    function triggerPopupWithUrl(url, filterById, headerText) {
        if (headerText == undefined) {
            headerText = '';
        }
        if (url == undefined) {
            alert('ERROR : Cannot load content without url.');
        }
        retrieveDiv(); // Confirm page has the div.
        $('#' + POPUP_HEADER).html(headerText);
        $('#' + POPUP_CONTENT).html('');
        showPopupDiv();

        if (filterById == undefined || filterById == '') {
        } else {
            url = url + ' #' + filterById;
        }
        $('#' + POPUP_CONTENT).load(url, null,
            function(responseText, textStatus, XMLHttpRequest) {
                if (XMLHttpRequest.status != 200) {
                    $('#' + POPUP_CONTENT).html(responseText);
                }
            });
//            Uncomment to see the content returned in a javascript debugger :
//            $.get(url, function(data) {
//                var returnData = data;
//            });
    }

//    function popupWindowOpen(appType, linkArgs) {
//        //window.open(<%=sg.getLableLink("helpEticket").getTargetParam()%>)"
//        //getLableLink return example : '/presentation/frameset/info.jsp?type=Editorial&name=DeliveryHelpEticket&ums=1', 'DeliveryHelp', 'status=no,toolbar=no,menubar=no,scrollbar=yes,location=no,width=520,height=450,left=80,top=80'
//
//        if (appType == 'desktop') {
//            window.open(linkArgs);
//        } else {
//            var args = linkArgs.split(',');
//            var linkUrl = args[0]
//            var headerText = args[1]
//            triggerPopupWithUrl(linkUrl, 'popupBody', headerText)
//        }
//    }
//
//
//    function popupWindowOpen(link, title, unwrapTagId) {
//        triggerPopupWithUrl(link, title, unwrapTagId)
//    }


    return {setupPopups:setupPopups,
            hidePopupDiv:hidePopupDiv};
})();

