﻿    function DateToTriplet(d)
    {
        var t = new Array(d.getFullYear(), d.getMonth() + 1, d.getDate());
        return t;
    }
    function trim(tx) {
        return tx.replace(/^\s+|\s+$/g,"");
    }
    function ltrim(stringToTrim) {
        return tx.replace(/^\s+/,"");
    }
    function rtrim(stringToTrim) {
        return tx.replace(/\s+$/,"");
    }
   
    function ShowTooltip(tooltip)
    {
        window.setTimeout(function()
        {         
            tooltip.show();
        }, 0);
    }   
    function openWindow(url, name)
    {
        var curWnd = GetRadWindow();
        if (curWnd) {
            var wnd = curWnd.BrowserWindow;
            if (wnd == null) {
                wnd = curWnd.get_windowManager();
            }
            if (wnd) {
                var mWnd = wnd.radopen(url, name);
                return mWnd;
            }
        }
        return radopen(url, name);
    }
    
//New stuff from master page

function GetRadWindow() {
    var oWindow = null;
    if (window.radWindow) {
        oWindow = window.radWindow;
    }
    else if (window.frameElement != null) {
        if (window.frameElement.radWindow) {
            oWindow = window.frameElement.radWindow;
        }
    }
    return oWindow;
}

function refreshRadWindow(windowName) {
    var window = GetRadWindowManager();
    if (window != null) {
        var chatWindow = window.getWindowByName(windowName);
        if (chatWindow != null) {
            chatWindow.reload();
        }
    }
}

function closeRadWindow() { // Close Window
    var wnd = GetRadWindow();
    setTimeout(function () { if (wnd) { wnd.Close(); } }, 0);
}

function openRadWindowWithReturn(url, width, height, refresh, name,modal) 
{
    return BuildWindow(url, width, height, refresh, name,modal);
}

function openRadWindow(url, width, height, refresh, name,modal) 
{
    BuildWindow(url, width, height, refresh, name,modal);
}

function BuildWindow(url, width, height, refresh, name,modal) 
{
    try {
        var windowWidth = 650;
        var windowHeight = 400;
        var windowName = "OnlyOneWindowAtATime";
        var refreshParent = false;

        if (name != null) {
            windowName = name;
        }

        if (width) {
            windowWidth = width;
        }

        if (refresh) {
            if (refresh == true) {
                refreshParent = true;
            }
        }

        if (height) {
            windowHeight = height;
        }

        var dialog = radopen(url, windowName);
        dialog.set_width(windowWidth);
        dialog.set_height(windowHeight);
        dialog.center();
        if (modal != null ) {
            dialog.set_modal(modal);
        }
        else {
            dialog.set_modal(true);
        }
        if (refreshParent == true) {
            dialog.add_close(refreshWindow);
        }

        setTimeout(function () { dialog.restore(); dialog.setActive(true); });
    }
    catch (err) {
        alert(err.description + "\n Try again please.");
    }
    return dialog;
}

// Event occurs when user click on RadTabStrip.
function onTabSelecting(sender, args)
{
    if (args.get_tab().get_pageViewID())
    {
        args.get_tab().set_postBack(false);
    }
}

function getToolBarMenu() {
    var menuData = {
        "searchLoads": { "Width": 670, "Height": 450, "URL": "addUpdateSearches.aspx?type=Loads"},
        "searchLoadBids": { "Width": 670, "Height": 450, "URL": "addUpdateSearches.aspx?type=LoadBids" },
        "searchTrucks": { "Width": 670, "Height": 450, "URL": "addUpdateSearches.aspx?type=Trucks" },
        "searchLanes": { "Width": 670, "Height": 450, "URL": "addUpdateSearches.aspx?type=Lanes"},
        "favoriteLoadSearch": { "Width": 670, "Height": 510, "URL": "FavoriteSearches.aspx?type=Loads"},
        "favoriteTruckSearch": { "Width": 670, "Height": 510, "URL": "FavoriteSearches.aspx?type=Trucks"},
        "favoriteLaneSearch": { "Width": 670, "Height": 510, "URL": "FavoriteSearches.aspx?type=Lanes"},
        "favoriteLoadPosts": { "Width": 670, "Height": 560, "URL": "Favorites.aspx?type=Loads"},
        "favoriteTruckPosts": { "Width": 670, "Height": 560, "URL": "Favorites.aspx?type=Trucks"},
        "favoriteLanePosts": { "Width": 670, "Height": 560, "URL": "Favorites.aspx?type=Lanes" },
        "postLoads": { "Width": 670, "Height": 560, "URL": "addUpdateSingleLoads.aspx" },
        "postLoadBids": { "Width": 670, "Height": 560, "URL": "addUpdateSingleLoadBids.aspx" },
        "postTrucks": { "Width": 670, "Height": 560, "URL": "addUpdateSingleTrucks.aspx"},
        "postLanes": { "Width": 670, "Height": 560, "URL": "addUpdateSingleLanes.aspx"},
        "postTruckBids": { "Width": 670, "Height": 560, "URL": "AddUpdateSingleTruckBids.aspx"},
        "historicalLoads": { "Width": 770, "Height": 510, "URL": "HistoricalPostings.aspx?type=Loads" },
        "historicalTrucks": { "Width": 770, "Height": 510, "URL": "HistoricalPostings.aspx?type=Trucks" },
        "historicalLanes": { "Width": 770, "Height": 510, "URL": "HistoricalPostings.aspx?type=Lanes" }
    }
    return menuData;
}

function toolbarMenu_Click(sender, eventArgs) {

    var menuData = getToolBarMenu();
    var menuItem = menuData[eventArgs.get_item().get_value()];
    openRadWindow(menuItem.URL, menuItem.Width, menuItem.Height);
}
function reportMenu_Click(sender, args)
{
    var myWidth = 650;
    var myHeight = 400;
    switch(args.get_item().get_value())
    {
        case "non_payment":
        {
            myWidth = 630;
            myHeight = 600;
            openRadWindow("/Report/NonPayment.aspx", myWidth, myHeight);
            break;
        }
        case "daystopay":
        {
            myWidth = 630;
            myHeight = 600;
            openRadWindow("/Report/DaysToPay.aspx", myWidth, myHeight);
            break;
        }
        case "broker_performance_report":
        {
            myWidth = 630;
            myHeight = 600;
            openRadWindow("/Report/BrokerPerformanceReport.aspx", myWidth, myHeight);
            break;
        }
        case "carrier_performance_report":
        {
            myWidth = 630;
            myHeight = 600;
            openRadWindow("/Report/CarrierPerformanceReport.aspx", myWidth, myHeight);
            break;
        }
        default:
        {
            //Do nothing
            break;
        }
    }
}
function manageVisitedCookie(SearchType, SearchID)
{
    if(SearchID != null && SearchID != "")
    {
        var cookieName = SearchType + "Visited";
        var id = SearchID;
        ///Retrieve the value section of the cookie
        var cookieValue = getCookie(cookieName);
        if(cookieValue == "")
        {
            ///If it doesn't have a value create a new cookie
            setCookie(cookieName, id, 30);
        }
        else
        {
            ///Is the ID already set in the cookie
            //if(cookieValue.cont)
            //{
                ///If it does have a value append the new value to the cookie
                setCookie(cookieName, cookieValue + "," + id, 30);
            //}
        }
    }
    return false;
}
function getCookie(cookieName)
{
    ///Are there any cookies
    if (document.cookie.length>0)
    {
        ///Does our specific cookie exist
        cookieValueStart=document.cookie.indexOf(cookieName + "=");
        if (cookieValueStart != -1)
        {
            ///This value figures out where the value starts
            cookieValueStart = cookieValueStart + cookieName.length+1;
            ///This value figures out where the value ends. The ; would indicate and expire date
            cookieValueEnd = document.cookie.indexOf(";",cookieValueStart);
            if (cookieValueEnd == -1) 
            {
                ///If for some reason there is no expire date, just set it to the cookie length
                cookieValueEnd = document.cookie.length;
            }
            return unescape(document.cookie.substring(cookieValueStart, cookieValueEnd));
        }
    }
    return "";
}

function setCookie(cookieName,value,expiredays)
{
    ///Grab the current date
    var exdate=new Date();
    ///Add the days that are passed in
    exdate.setDate(exdate.getDate()+expiredays);
    ///Set a new cookie
    document.cookie = cookieName + "=" + value+";path=/;" + ((expiredays == null) ? "" : ";expires=" + exdate+";");
}

function deleteCookie(cookieName) {
    document.cookie = cookieName + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}

function Searching_PageSizeChanging(sender, eventArgs)
{
    var item = eventArgs.get_item();
    setCookie("SearchingPageSize",item.get_text(),30);
}
function Posting_PageSizeChanging(sender, eventArgs)
{
    var item = eventArgs.get_item();
    setCookie("PostingPageSize",item.get_text(),30);
}
function OpenAUP()
{
    myWidth = 630;
    myHeight = 600;
    openRadWindow("/Content/en-US/AUP.htm", myWidth, myHeight);
}

function findParameterInURL(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}


function bustFrameToAuthenticateRedirectingToParent() {
    if (parent.location.href != location.href) {
        parent.location.href = "/Authenticate.aspx?redirect=" + escape(parent.location.href)
    }
}

function getUrlQueryItems() {
    var items = [];
    var query;

    var queryItems = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for (var i = 0; i < queryItems.length; i++) {
        query = queryItems[i].split('=');
        items.push(query[0]);
        items[query[0]] = query[1];
    }
    return items;
}

function OpenRedirector(action,url) {
    var newWindow = window.open('');
    var post = "<html><head></head><body><form id='formRedirect' method='post' action='"+action+"'><input type='hidden' name='url' value='" + url + "' /></form><script type='text/javascript'>document.getElementById('formRedirect').submit();</script></body></html>";
    newWindow.document.write(post);
}

if (findParameterInURL('Print') == 'true') {
    window.print();
}


function isInputKeyCode(keyCode) {
    var result = false;
    if ((keyCode >= 48 && keyCode <= 90)
        || (keyCode >= 93 && keyCode <= 111)
        || (keyCode >= 186 && keyCode < 222)) {
        result = true;
    }
    return result;
}


/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
if (jQuery)
{
    jQuery.cookie = function(key, value, options) {

        // key and at least value given, set cookie...
        if (arguments.length > 1 && String(value) !== "[object Object]") {
            options = jQuery.extend({ }, options);

            if (value === null || value === undefined) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=',
                options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || { };
        var result, decode = options.raw ? function(s) { return s; } : decodeURIComponent;
        return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
    };
}


function CountCharacters(field, maxcharacters) {
    if (field.value.length > maxcharacters) {
        field.value = field.value.substring(0, maxcharacters);
        alert("Sorry, " + maxcharacters + " characters maximum allowed.");
        return false;
    }
    else {
        return true;
    }
}

//http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery
String.prototype.format = function () {
    var s = this,
                i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

function get_time_difference_in_seconds(earlierDate, laterDate) {
    return Math.floor((laterDate.getTime() - earlierDate.getTime()) / 1000);
}


function stringToDate(dateTime) {
    var date = dateTime.split("-");
    return new Date(date[0], date[1] - 1, date[2], date[3], date[4], date[5]);
}

function openBillingWindow(url) {
    var wnd = parent.openRadWindowWithReturn(url, 800, 400, false, 'BillingWindow', true);
    setTimeout(function () { wnd.setActive(true) });
    return false;
}

function openInvoiceWindow() {
    var wnd = openRadWindowWithReturn('/Profiles/Invoice.aspx', 850, 730, false, 'Invoice', true);
    wnd.add_close(function (sender, eventArgs) {
        var arg = eventArgs.get_argument();
        if (arg) {
            openBillingWindow(arg);
        }
    });
    return false;
//    var dialog = parent.radopen(, 'Invoice');
//    dialog.set_width(850);
//    dialog.set_height(730);
//    dialog.center();
//    dialog.set_modal(true);

//    dialog.add_close(function (sender, eventArgs) {
//        var arg = eventArgs.get_argument();
//        if (arg) {
//            setTimeout(function () {
//                openBillingWindow(arg);
//            });
//        }
//    });

//    setTimeout(function () { dialog.restore(); dialog.setActive(true); });
}

function OpenVeleroWindow() {
    this.newWindow = window.open('http://c.velaro.com/visitor/requestchat.aspx?siteid=10123&showwhen=inqueue', 'OnlineChatSoftware', 'toolbar=no,location=no,directories=no,menubar=no,status=no,scrollbars=no,resizable=yes,replace=no,width=600,height=600');
    this.newWindow.focus();
    this.newWindow.opener = window;
}
function BondDisplay(aType) {
    var theWidth = 650;
    var theHeight = 450;
    var oWnd = window.radopen("/Searches/BondLoadSplash.aspx?Type=" + aType);
    oWnd.set_height(theHeight);
    oWnd.set_width(theWidth);
}

function ButtonTimer() {
    $('.timedButton').hide();
    var t = setTimeout("TimeButton()", 10000);

}

function TimeButton() {
    $('.timedButton').show();
}

function buttonSearch_ClientClick() {
    $('.timedButton').hide();
    $('#loadingButtonDisable').show();
}
