﻿/// <reference path="jquery-telerik-vsdoc.js"/>

var windowHandle = -1;
var mouseButtonClicked = 2;

function checkButton(event) {
    mouseButtonClicked = event.button;
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function simulates a Tab keypress when an Enter key is pressed.
* 
*/
///////////////////////////////////////////////////////////////////////////////////////////		
function simulateTabKeyPress(e) {
    if (window.event) //IE
    {
        if (event.keyCode == 13) {
            event.keyCode = 9;
        }
    }
}

function attachFaceBoxBehavior() {
    //select all the a tag with name equal to modal   
    $('a[name=modal]').click(function(e) {
        //Cancel the link behavior   
        e.preventDefault();
        //Get the A tag   
        var id = $(this).attr('href');

        //Get the screen height and width   
        var maskHeight = $(document).height() - 5;  // Subtract 5 to not show the scrollbars
        var maskWidth = $(window).width() - 5;

        //Set height and width to mask to fill up the whole screen   
        $('#mask').css({ 'width': maskWidth, 'height': maskHeight });

        //transition effect        
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo("slow", 0.8);

        //Get the window height and width   
        var winH = $(window).height();
        var winW = $(window).width();

        //Set the popup window to center   
        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);

        //transition effect   
        $(id).fadeIn(2000);

    });

    //if close button is clicked   
    $('.window .close').click(function(e) {
        //Cancel the link behavior   
        e.preventDefault();
        $('#mask, .window').hide();
    });

    //if mask is clicked   
    $('#mask').click(function() {
        $(this).hide();
        $('.window').hide();
    });
}

// This function is used to set the watermark text for a textbox
function waterMark(txt, evt, txtValue) {
    var defaultText = "Enter Search Value";
    var strTextValue = ((txtValue != null) && (txtValue != "")) ? txtValue : defaultText;
    if (txt.value.length == 0 && evt.type == "blur")
    {
        txt.style.color = "gray";
        txt.style.fontWeight = "Normal";
        txt.value = defaultText;
    }
    if (txt.value == defaultText && evt.type == "focus") 
    {
        txt.style.color = "#000099";
        txt.style.fontWeight = "Bold";
        txt.value = "";
    }
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function uses a regular expression to extract the server control ID prefix
*			for a given control ID.
* 
* Parameters:
*				controlID:	The control ID of the control to extract.
*/
///////////////////////////////////////////////////////////////////////////////////////////		
function extractControlIDPrefix(controlID) {
    // Create a regular expression to locate the prefix.
    var regEx = /(\w*__\w*_)|(\w*_)/;

    // The 1-D array will contain the patterns located within the regex match.
    var array = regEx.exec(controlID);

    // Ensure that a match was found.
    if ((array != null) && (array.length >= 1)) {
        return array[0];
    }
    else {
        return "";
    }
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function creates/destroys the needed element based on the visibility of the container Element
* 
* Parameters:  elementHTML: The HTML for the element that needs to be created
*              elementID :  The ID for th element that needs to be destroyed if the container element is not being shown
*              containerElementID : The ID for the container element
*/
///////////////////////////////////////////////////////////////////////////////////////////	
function createElementObject(elementTag, elementID, elementClass, containerElementID) {
    //get the container element
    var containerElementObj = $get(containerElementID);
    if (containerElementObj != null) {   //if the container element is being shown, then create the needed element and add to the container
        if (containerElementObj.style.display == "block") {
            var elementObj = document.createElement(elementTag);
            elementObj.id = elementID;
            elementObj.className = elementClass;

            containerElementObj.appendChild(elementObj);
        }
        // if the container element is not being shown then remove the element 
        else {
            destroyElementObject(elementID);
        }
    }
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function destroys a given element 
* 
* Parameters:  elementID : The ID for the element that needs to be destroyed
*/
///////////////////////////////////////////////////////////////////////////////////////////	
function destroyElementObject(elementID) {
    var elementObj = $get(elementID);
    if (elementObj != null) {
        try {
            // Removes the object from the document hierarchy.
            // IE
            elementObj.removeNode(true);
        }
        catch (err) {
            // Firefox
            elementObj.parentNode.removeChild(elementObj);
        }
    }
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function sets the src for a given iframe
* 
* Parameters:  iframeID : The ID for the iframe for which the src needs to be set
*               srcURL   : The src for the iframe
*/
///////////////////////////////////////////////////////////////////////////////////////////
function setIFrameSrc(iframeID, srcURL) {
    var iframeObj = $get(iframeID);

    if (iframeObj != null) {
        iframeObj.src = srcURL;
    }
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function toggles the visibility of the control that is passed into it 
* 
* Parameters:  toggleControlID
*/
///////////////////////////////////////////////////////////////////////////////////////////
function toggleControl(toggleControlID) {
    var toggleControl = document.getElementById(toggleControlID);

    if (toggleControl) {
        if (toggleControl.style.display == 'block') {
            toggleControl.style.display = 'none';
        }
        else {
            toggleControl.style.display = 'block';
        }
    }
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function toggles the visibility of the control that is passed into it 
and the image associated with the control
* 
* Parameters:  toggleControlID With Image
*/
///////////////////////////////////////////////////////////////////////////////////////////
function toggleControlWithImage(toggleControlID, imgControlID, imgShow, imgHide) {
    var toggleControl = document.getElementById(toggleControlID);
    var img = document.getElementById(imgControlID);

    if (toggleControl) {
        var visible = $("#" + toggleControlID + "").is(":visible");
        $("#" + toggleControlID + "").toggle("slow");
        if (visible == true) {
            img.src = "/dodweb/Common/Images/Icons/" + imgShow;
        }
        else {
            img.src = "/dodweb/Common/Images/Icons/" + imgHide;
        }
    }
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function hides the progress bar and shows the iframe.  This function is called
* after the load has been performed in the loadControl and the image showing the progress bar
* is to be hidden. 
* Parameters: imgProgressID
* Parameters: loadControlID
*/
///////////////////////////////////////////////////////////////////////////////////////////
function toggleProgress(imgProgressID, loadControlID) {
    var imgProgress = document.getElementById(imgProgressID);
    var loadControl = document.getElementById(loadControlID);

    if (imgProgress)
    { imgProgress.style.display = "none"; }
    if (loadControl)
    { loadControl.style.display = "block"; }
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function sets the element to the center of the screen 
* Parameters: iframeName
*/
///////////////////////////////////////////////////////////////////////////////////////////	    
function centerElementOnScreen(element) {
    var scrollTop = document.body.scrollTop;
    var scrollLeft = document.body.scrollLeft;

    var viewPortHeight = document.body.clientHeight;
    var viewPortWidth = document.body.clientWidth;

    if (document.compatMode == "CSS1Compat") {
        viewPortHeight = document.documentElement.clientHeight;
        viewPortWidth = document.documentElement.clientWidth;

        scrollTop = document.documentElement.scrollTop;
        scrollLeft = document.documentElement.scrollLeft;
    }

    var topOffset = Math.ceil(viewPortHeight / 2 - element.offsetHeight / 2);
    var leftOffset = Math.ceil(viewPortWidth / 2 - element.offsetWidth / 2);

    var top = scrollTop + topOffset - 40;
    var left = scrollLeft + leftOffset - 70;

    element.style.position = "absolute";
    element.style.top = top + "px";
    element.style.left = left + "px";
    element.style.display = 'block';
}

// This function is called when the radajaxmanager on the master fires an ajax request.
function onAJAXManagerRequestStart() {
    var loadingPanel = $get('ctl00_masterAjaxLoadingPanel');
    if (loadingPanel != null) {
        centerElementOnScreen(loadingPanel);
    }
}

// This function is called when the radajaxmanager completes receiving the response for an ajax request
function onAJAXManagerResponseEnd() {
    var loadingPanel = $get('ctl00_masterAjaxLoadingPanel');
    if (loadingPanel != null) {
        loadingPanel.style.display = 'none';
        loadingPanel = null;
    }
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function sets the source and target of the secondary report  
* Parameters: source = The source of the frame being set
target = The target of the frame id
*/
///////////////////////////////////////////////////////////////////////////////////////////	
function displaySecondaryReport(source, target) {
    // Gets the current mouse location
    x = event.clientX;
    y = document.documentElement.scrollTop + event.clientY;

    // Get controls elements of the form to be dynamically changed
    var iframeSecondaryReport = parent.document.getElementById(target);
    var divSecondaryReport = parent.document.getElementById('divSecondaryReport');
    var imgProgress = parent.document.getElementById('imgSecondaryProgress');

    // Set the values of the controls         
    imgProgress.style.display = "block";
    divSecondaryReport.style.display = "block";
    divSecondaryReport.style.top = y + 175;
    divSecondaryReport.style.bottom = x;
    iframeSecondaryReport.src = source;

    return;
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function checks the maxlength of the control and sets the label counter 
accordingly  
* Parameters: objID = The ID of the control to check the max length
counterControlID = The ID for the label to display the characters remaining
maxLength = The maximum length for the textbox/textarea
*/
///////////////////////////////////////////////////////////////////////////////////////////	
function IsMaxLength(objID, counterControlID, maxLength) {
    var lblCounter = $get(counterControlID);
    var obj = $get(objID);

    if ((lblCounter != null) && (obj != null)) {
        // Set the Counter Control value
        lblCounter.value = (maxLength - obj.value.length);

        // If the Lenght of the text is greater than the Max Length remove the characters
        if (obj.value.length > maxLength) {
            obj.value = obj.value.substring(0, maxLength);

            if (lblCounter.value < 0) {
                lblCounter.value = 0;
            }

        }
    }
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function populates the hidden control from a another control (ex. ListBox)
* Parameters: listbox = The control to get the value from to populate the hidden box
hiddenControl = The hidden control that gets populated from the control
	               
*/
///////////////////////////////////////////////////////////////////////////////////////////	    
function listBoxToTextBox(listbox, hiddenControl) {
    // Extract the control prefix if the fieldID has been specified.
    var controlIDPrefix = extractControlIDPrefix(listbox);
    // Get the listbox control
    var selectedValue = document.getElementById(listbox);
    // Get the hidden textbox control
    var hiddenControl = document.getElementById(controlIDPrefix + hiddenControl);
    // Loop thru to get the selected value of the listbox
    for (var i = 0; i < selectedValue.options.length; i++) {
        if ((selectedValue.options[i].selected == true)) {
            // Set the hidden textbox to the selected value of the listbox
            hiddenControl.value = selectedValue.options[i].text;
        }
    }
}


/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function checks the maxlength of the control and sets the label counter 
accordingly  
* Parameters: fieldID = The hyperlink control id
addressID = The address control id
cityID = The city control id
stateID = The state control id
zipID = The zip code control id
*/
///////////////////////////////////////////////////////////////////////////////////////////	    
function mapAddress(fieldID, addressID, cityID, stateID, zipID, mapType) {
    if (fieldID.length > 0) {
        // Extract the control prefix if the fieldID has been specified.
        var controlIDPrefix = extractControlIDPrefix(fieldID);

        if (controlIDPrefix.length > 0) {
            address = document.getElementById(controlIDPrefix + addressID);
            city = document.getElementById(controlIDPrefix + cityID);
            state = document.getElementById(controlIDPrefix + stateID);
            zip = document.getElementById(controlIDPrefix + zipID);

            if (address.value != '' && city.value != '' && state.value != '' && zip.value != '') {
                var address = address.value + ' ' + city.value + ' ' + state.value + ' ' + zip.value;

                if (mapType == 'google')
                    window.open("http://maps.google.com/maps?q=" + address, "Map");
                else if (mapType == 'live')
                    window.open("http://maps.live.com/default.aspx?v=2&where1=" + address, "Map");
            }
        }
    }
}

function doClick(buttonName, e) {
    //the purpose of this function is to allow the enter key to 
    //point to the correct button to click.
    var key;

    if (window.event)
        key = window.event.keyCode;     //IE
    else
        key = e.which;     //firefox

    if (key == 13) {
        //Get the button the user wants to have clicked
        var btn = document.getElementById(buttonName);
        if (btn != null) { //If we find the button click it
            btn.click();
            event.keyCode = 0
        }
    }
}


/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function returns the document width.  
* Parameters: doc
*/
///////////////////////////////////////////////////////////////////////////////////////////		    
function getDocWidth(doc) {
    var docWidth = 0, sh, oh;
    if (doc.width) docWidth = doc.width;
    else if (doc.body) {
        if (doc.body.scrollWidth) docWidth = sh = doc.body.scrollWidth;
        if (doc.body.offsetWidth) docWidth = oh = doc.body.offsetWidth;
        if (sh && oh) docWidth = Math.max(sh, oh);
    }
    return docWidth;
}

/* ///////////////////////////////////////////////////////////////////////////////////////////
* Purpose:  This function sets the iframe width to the internal document width.  
* Parameters: iframeName
*/
///////////////////////////////////////////////////////////////////////////////////////////	
function setIframeWidth(iframeName) {
    var iframeWin = window.frames[iframeName];
    var iframeEl = document.getElementById ? document.getElementById(iframeName) : document.all ? document.all[iframeName] : null;
    if (iframeEl && iframeWin) {
        iframeEl.style.width = "auto"; // helps resize (for some) if new doc shorter than previous  
        var docWidth = getDocWidth(iframeWin.document);
        // need to add to width to be sure it will all show
        if (docWidth) iframeEl.style.width = docWidth + 30 + "px";
    }
}

function resizeIFrameHeightHelper(iframe) {
    if (iframe != null) {
        var newHeight = "100%";

        // Is this a slidingpanel <div>?
        if ($(iframe).parent().hasClass("slidingpanel")) {
            newHeight = ($(iframe).parent().height());
        }
        else {
            // Use the jQuery get() method to retrieve the first DOM element within the <iframe>.
            var firstDOMElement = iframe.get(0);

            if (firstDOMElement != null) {
                var iframeDoc = null;

                // Retrieve the document object for the page or frame.
                // MSIE 8 uses the new contentDocument property, the W3C DOM2 standard property.
                // Older MSIE versions use the proprietary contentWindow property.
                if (firstDOMElement.contentDocument) {
                    iframeDoc = firstDOMElement.contentDocument;
                }
                else if (firstDOMElement.contentWindow) {
                    iframeDoc = ((firstDOMElement.contentWindow.document) ? (firstDOMElement.contentWindow.document) : null);
                }

                if (iframeDoc != null) {
                    // Add 20 pixels to account for the content-wrapper's margin-top offset
                    newHeight = ($("body", iframeDoc).height() + 20);
                }
            }
        }

        // Set the new height attribute value for the <iframe> element.
        $(iframe).height(newHeight);
    }
}


function resizeIFrameHeight() {
    // Bind the custom resize function to the load event for all <iframe> elements.
    $(".iframeResize").bind('load', function(event) {
        // Resize the iframe immediately.
        resizeIFrameHeightHelper($(this));
        // Set a 200 ms delay to resize again to accomodate slower loading pages.
        setTimeout(function() { resizeIFrameHeightHelper($(this)) }, 200);
    });
    // Bind the custom resize function to the load event for all <iframe> elements.
    $(".iframeResize").bind('mouseover', function(event) {
        // Resize the iframe immediately.
        resizeIFrameHeightHelper($(this));
    });    
}

function loadframe(link, control) {
    var iframe = document.getElementById(control);
    iframe.src = link;
    setIframeWidth(iframe);
}

String.prototype.titleCase = function() {
    var str = "";
    var wrds = this.split(" ");
    var i = 0;
    for (keyvar in wrds) {
        if (i == 0)
        {
            str += wrds[keyvar].substr(0, 1).toUpperCase() + wrds[keyvar].substr(1, wrds[keyvar].length);
        }
        else
        {
            str += ' ' + wrds[keyvar].substr(0, 1).toUpperCase() + wrds[keyvar].substr(1, wrds[keyvar].length);
        }
        i++;
    }
    return str;
}

function CloseAndRebind() {
    GetRadWindow().Close();
}

function GetRadWindow() {
    var oWindow = null;
    if (window.radWindow) oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog
    else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow; //IE (and Moz as well)

    return oWindow;
}   