/*----------------------------------------------------------
How to put it in the header
<SCRIPT LANGUAGE="JavaScript" SRC="resources/javascripts/pop_window.js"></SCRIPT>

How to use in a link
<a href="javascript:makePopUpWin('filename.ext',width,height,features)">
Feature options:
0 = Menubar only
1 = Menubar and toolbar
2 = Menubar, status, resizable, scrollbars
3 = No menubar, no status bar, not resizable, no scrollbars
4 = scrollbars only
Example:<a href="javascript:makePopUpWin('UserContactProfile.aspx',450,185,3)">
__________________________________________________________*/
// Make popup window using specified sizes in the function
function initArray() {
    for (var i = 0; i < initArray.arguments.length; i++)
        this[i] = initArray.arguments[i];
    this.length = initArray.arguments.length;
}


//By default IE 7 does not respect 'status' and 'location' settings
//Following option needs to be enabled to control above two setting
//Tools->Internet Options->Security tab
//  Click Internet, then Custom Level
//  Scroll down to Miscellaneous
//  Scroll down to
//  "Allow websites to open windows without address or status bars"

var chrome = new initArray(
 "menubar",
 "menubar,toolbar",
 "menubar,status,resizable,scrollbars",
 "",
 "scrollbars",
 "resizable,scrollbars",
 "status=no,toolbar=no,menubar=no,location=no"
 );



var popUpWin = '';
var url = '';
var winFeatures = '';
var dateObj = new Date();

var newWin = null, iframe = null;

function findAndClosePopUpWin() {
    var IsParentAnIFrame = false;
    if (parent.frameElement && parent.frameElement.tagName && parent.frameElement.tagName.toUpperCase() == "IFRAME")
        IsParentAnIFrame = true;
    //if this is indexmain, find main frame and close, otherwise is a standalone page, such as a popup
    if (top.location.href.indexOf("indexmain.aspx") > -1 && !IsParentAnIFrame)
        top.main.closePopUpWin();
    else
        parent.closePopUpWin();
}

function closePopUpWin() {
    //since popup win is in iframe, need relative path to document
    var bodyTags = document.getElementsByTagName("body");
    if (bodyTags != null && bodyTags[0] != null)
        bodyTags[0].removeChild(newWin);

    newWin = null;
    iframe = null;
}

function include_dom(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}

var included_files = new Array();

function include_once(script_filename) {
    if (!in_array(script_filename, included_files)) {
        included_files[included_files.length] = script_filename;
        include_dom(script_filename);
    }
}

function in_array(needle, haystack) {
    for (var i = 0; i < haystack.length; i++) {
        if (haystack[i] == needle) {
            return true;
        }
    }
    return false;
}

/*Gets window size*/
function GetClientSize() {
    //debugger;
    var dimensions = { width: 0, height: 0 };
    if (window.innerWidth && window.innerHeight) { //innerHeight is a Non-IE property
        dimensions.width = window.innerWidth;
        dimensions.height = window.innerHeight;
    } else if (document.documentElement) { //documentElement is IE only 
        dimensions.width = document.documentElement.clientWidth;
        dimensions.height = document.documentElement.clientHeight;
    }
    return dimensions;
};




function makeDHTMLPopup(url, wide, high, pClientX, pClientY) {
    if (wide == null) wide = 395;
    if (high == null) high = 117;
    if (newWin != null) closePopUpWin();
    
    newWin = iframe = document.createElement("iframe");
    iframe.setAttribute("id", "iframe1");
    iframe.style.zIndex = 9999;
    iframe.style.border = 0 + 'px';
    var size = GetClientSize()
    document.getElementsByTagName("body")[0].appendChild(newWin);

    //create script tag for draggable iframe and add it to this page also
    include_dom("../resources/javascripts/dragiframe.js");

    newWin.style.position = "absolute";
    newWin.style.width = iframe.style.width = wide + 'px';
    newWin.style.height = iframe.style.height = high + 'px';
    newWin.style.top = newWin.style.left = 0 + 'px';


    var clientX = 0, clientY = 0;
    if (pClientX == null && pClientY == null) {
        clientX = event.clientX - wide + 20 ;
        clientY = event.clientY - 15 ;
    } else {
        clientX = pClientX;
        clientY = pClientY;
    }


    //Find out how close the mouse is to the corner of the window
    //var rightedge = document.body.clientWidth - clientX; //clientWidth, clientHeight is IE specific
    //var bottomedge = document.body.clientHeight - clientY;
    var rightedge = size.width - clientX;
    var bottomedge = size.height - clientY;

    //if the horizontal distance isn't enough to accomodate the width of the context menu
    if (rightedge < newWin.offsetWidth)
    //move the horizontal position of the menu to the left by it's width
        rightedge = document.body.scrollLeft + clientX - newWin.offsetWidth;
    else
    //position the horizontal position of the menu where the mouse was clicked
        rightedge = document.body.scrollLeft + clientX;

    //correct for rightedge being off the screen (negative)
    rightedge = (rightedge < 0 ? 5 : rightedge);
    newWin.style.left = rightedge + 'px';

    //same concept with the vertical position
    if (bottomedge < newWin.offsetHeight)
        bottomedge = document.body.scrollTop + clientY - newWin.offsetHeight;
    else
        bottomedge = document.body.scrollTop + clientY;

    bottomedge = (bottomedge < 0 ? 5 : bottomedge);
    newWin.style.top = bottomedge + 'px';

    iframe.src = url;
    iframe.allowTransparency = 'true'; //IE specific?
}

// 08/06/07  Chandra Bhumireddy
function makePopUpWin(url, wide, high, winFeatures) {
    var tall = high + 5;  // adjust for spacing to border above and below picture
    var side = wide + 5;  // adjust for spacing to border on sides of picture

    // Do not show popup if the  url is not passed
    if (url == undefined || url == "")
        return;

    //alert(x);

    if (popUpWin && !popUpWin.closed) {
        popUpWin.close();
    }

    popUpWin = window.open(url, 'newWin' + dateObj.getTime(), chrome[winFeatures] + ',height=' + tall + ',width=' + side);
    
    if (!popUpWin) {
        //        if (url.indexOf("ValidateLoginTest.aspx") == -1) {
        //            if (confirm("Your browser does not appear to support popups - Click the Ok button to leave this page and do a browser check or Cancel to ignore this problem.")) {
        //                top.document.location.href = "../Core/ValidateLoginTest.aspx?ReDirURL=%2E%2E%2FCore%2Fcreate%2Da%2Dproject1%2Easp&Step=1&Force=1";
        //            }
        //        } else {
        alert("Your browser does not support popups. Please click Ok on this dialog and read the directions on this page.");
        top.document.location.href = "../Core/ValidateLoginTest.aspx?ReDirURL=%2E%2E%2FCore%2FProjectList%2Easpx&Force=1";
        //}
    }
}


// 08/13/07  Chandra Bhumireddy
function makePopUpWinReuse(url, name, wide, high, winFeatures) {
    var tall = high + 5;  // adjust for spacing to border above and below picture
    var side = wide + 5;  // adjust for spacing to border on sides of picture

    // Do not show popup if the  url is not passed
    if (url == undefined || url == "")
        return;


    //	if (popUpWin && !popUpWin.closed) {
    //	
    //	    popUpWin.onunload="";
    //		popUpWin.close();
    //	}

    popUpWin = window.open(url, name, chrome[winFeatures] + ',height=' + tall + ',width=' + side);
    if (!popUpWin) {
        //        if (url.indexOf("ValidateLoginTest.aspx") == -1) {
        //            if (confirm("Your browser does not appear to support popups - Click the Ok button to leave this page and do a browser check or Cancel to ignore this problem.")) {
        //                top.document.location.href = "../Core/ValidateLoginTest.aspx?ReDirURL=%2E%2E%2FCore%2Fcreate%2Da%2Dproject1%2Easp&Step=1&Force=1";
        //            }
        //        } else {
        alert("Your browser does not support popups. Please click Ok on this dialog and read the directions on this page.");
        top.document.location.href = "../Core/ValidateLoginTest.aspx?ReDirURL=%2E%2E%2FCore%2FProjectList%2Easpx&Force=1";
        //        }
    }
}

function update() {
    popUpWin.document.open();
}

//.NET length validation functionality
function validateLength(oSrc, args) {
    var theVal = args.Value + "";

    if (theVal.length <= parseInt(oSrc.maxlength)) {
        args.IsValid = true;
    } else {
        args.IsValid = false;
    }
}

function selectAllItems(isChecked, checkboxName) {
    var ItemIds = eval(checkboxName);

    if (ItemIds) {
        var count = ItemIds.length;

        if (count) {
            for (var i = 0; i < count; i++) {
                ItemIds[i].checked = isChecked;
            }
        } else {
            ItemIds.checked = isChecked;
        }
    }
}

function ConstMgmtMenuLink(ConstMgmtId, ConstMgmtPage) {
    if ((top.frames) && (top.frames.length) && (top.frames.length > 1)) {
        top.frames[1].showAllFiles(false); //close all
        top.frames[1].toggleChildItemsShown(ConstMgmtId, true, true); //open single item
    }
    document.location.href = ConstMgmtPage; //send main page
}
function editProject(ProjectId) {
    window.open('../Core/ProjectDetails.aspx?Skin=External&ProjectId=' + ProjectId);
}
function gotoProject(ProjectId) {
    window.open('../Core/ProjectList.aspx?ProjectId=' + ProjectId);
}

function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

function selectAllText(textbox) {
    var oRange = textbox.createTextRange();
    oRange.moveStart('character', 0);
    oRange.moveEnd('character', textbox.value.length);
    oRange.select();
}

//We have to account for IE and non-IE browser implementation of XML Parcer
function GetXMLObject(XMLString) {
    try {
        if (window.ActiveXObject) { //IF IE
            var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";
            xmlDoc.loadXML(XMLString);

        } else { //all others
            var xmlParser = new DOMParser();
            var xmlDoc = xmlParser.parseFromString(XMLString, "text/xml");
        }
    }
    catch (Err) {
        window.alert("Browser does not support XML parsing.");
        return false;
    }
    return xmlDoc;
}

//this function works just for those xml provided on server side and authors forgot to do UrlEncoding for them.
//It has two implementations for IE and non-IE
function GetEscapedXmlSingleNodeData(xmlTextArg, nodePath) {

    if (window.ActiveXObject) {
        //selectSingleNode method only works for IE :(
        var escapeText = xmlTextArg.replace(/&/g, '&amp;');
        var XML = GetXMLObject(escapeText);
        var nodeText = XML.selectSingleNode(nodePath).text;
        nodeText = nodeText.replace(/&amp;/g, '&');
        return nodeText;
    }
    //For non-IE you need this.
    //else if (document.implementation && document.implementation.createDocument) {
    else {
        var XML = GetXMLObject(xmlTextArg);
        var nodeText = XML.evaluate(nodePath, XML, null, XPathResult.ANY_TYPE, null)
        var result = nodeText.iterateNext();

        while (result && (result.childNodes[0]) != undefined) {
            result = result.childNodes[0].nodeValue;
            return result;
            result = nodeText.iterateNext();
        }
    }
}


// Wayne Zhang, 2007-10-10
// This function is used to enable HidhSlides PopUp to inform its opener page to refresh 
// when the close button inside the popup is clicked.
// Note: It need to be HighSlides PopUp and with Iframe setting, and it won't work if you are still
//       doing some work on popup.
// Use:  example: <body onload="return AttachCloseEvent2HsPopupContainer(window, 'RefreshParentPage')">
function AttachCloseEvent2HsPopupContainer(sender, arg) {
    if (sender.parent) {
        var senderDocUrl = sender.document.url;
        var mainDoc = sender.parent.document;
        var mainDocUrl = mainDoc.url;
        var iframeArray = mainDoc.getElementsByTagName('iframe');

        var targetIframe = null;
        for (var i = 0; i < iframeArray.length; i++) {
            var tempIf = iframeArray[i];

            if (tempIf.src == sender.location.href) {
                targetIframe = tempIf;
                break;
            }
        }

        if (targetIframe != null) {
            var hsBody = targetIframe.parentNode;
            var hsMove = hsBody.previousSibling;
            var hsCloseControl = hsMove.firstChild;

            if (arg == 'RefreshParentPage') {
                //"<A class=control onclick=\"return hs.close(this)\" href=\"#\">Close</A>"
                hsCloseControl.setAttribute('href', 'javascript: location.reload(true); ');
                hsCloseControl.setAttribute('onclick', ''); //hs.Close(this);
            }

        }
    }
}
// -->

function importStylesheet(sheetUrl) {
    var ss = document.createElement("link");
    ss.rel = "stylesheet";
    ss.href = sheetUrl;
    ss.type = "text/css"; 
    document.getElementsByTagName("head")[0].appendChild(ss);
}


//JS to embed iPad css file to every page for iPad
//Since we need need to use the css only for iPad and Xoom, this is the cleanest way I know.
if (navigator.userAgent.indexOf('iPad') != -1) {
    //IE specific (Not needed but shown here for example if we need to add more)
    //if (document.createStyleSheet) {
    //    document.createStyleSheet('../resources/stylesheets/ie.css');
    //}
    //else {
    //Non IE
    importStylesheet("../resources/stylesheets/iPad.css");
    //}
}
else if (navigator.userAgent.indexOf('Xoom') != -1) {
    importStylesheet("../resources/stylesheets/Android.css");

}


if (navigator.userAgent.indexOf('Macintosh') != -1) { //Only desktop version of Mac
        importStylesheet("../resources/stylesheets/MacOS.css");
}

