﻿
// Input Character length limiter
function charLimiter(textboxName, displayboxName, limit) {
    $("#" + displayboxName).attr("class", "charLimit");
    var count = limit - ($("#" + textboxName).val().length);
    $("#" + displayboxName).html(count + " characters left");
    if (count < 0) {
        $("#" + displayboxName).html("Too many characters");
        $("#" + displayboxName).attr("style", "color:red;")
    }
}

//DatePicker
function datepicker(id) {
    $(document).ready(function () {
        $("#"+id).datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'dd-MM-yy'
        });
    });
}

function datepickerButtonPanel(id) {
    $(document).ready(function () {
        $("#" + id).datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'dd-MM-yy',
            showButtonPanel: true
        });
    });
}

//Dropdown time controls
function timeControlHtml(id){
    var hours = "Hour: <select id='calHour" + id + "' style='margin-right:20px;'>";
    for (var i = 1; i < 25; i++) {
        hours += "<option>" + i + "</option>";
    }
    hours += "</select>"
    var mins = "Minute: <select id='calMin"+id+"'>";
    for (var i = 1; i < 60; i++) {
        mins += "<option>" + i + "</option>";
    }
    mins += "</select>"
    return "<div style='text-align:center;' class='ft' >" + hours + mins + "</div>";
}
    

// Expandable Helper Boxes - Getting Started boxes
    function GSBuyBox(parent, width) {
        $("#" + parent).html(
        "        <div id='BlueFill' style='width:"+ width +"'> " +
        "            <span class='lth'></span><span class='rth'></span> " +
        "                <h1 id='BuyH1' class='clickLink'>Getting Started: How to Buy</h1> " +
        "                <div id='BuyDiv' style='padding-left:9px;padding-right:9px; display:none;'> " +
        "                    <p>Just three simple steps to buy:</p> " +
        "                    <strong>1.</strong> Search for Routes <a href='/PublicRoute/SearchRoutes'>here</a><br /><br /> " +
        "                    <strong>2.</strong> Click the Cart icon and enter your Sending IP and optionally a Tech Prefix.<br /><br /> " +
        "                    <strong>3.</strong> Go to <a href='/Subscriptions/'>My Rate Sheet Subscriptions</a> and download the Rate Sheet .csv file to load in to your switch.<br /> " +
        "                </div> " +
        "            <span class='lb'></span><span class='rb'></span> " +
        "        </div><br class='spacer' />");
    }
    
    function GSSellBox(parent, width) {
        $("#" + parent).html(
    "<div id='GreenFill' style='width:" + width + "'>" +
    "                <span class='lth'></span><span class='rth'></span>" +
    "                    <h1 id='SellH1' class='clickLink'>Getting Started: How to Sell</h1>" +
    "                    <div id='SellDiv' style='padding-left:9px;padding-right:9px; display:none;'>" +
    "                        <p>Just three easy steps to start selling:</p>" +
    "                        <strong>1.</strong> Review your Rate Sheet file. <br />For formatting guidelines see:<br /> <a href='/FAQ/Seller#RateSheetFormat'>\"Does a Rate Sheet file need to be in a specific format when I upload it?\"</a><br /><br />" +
    "                        <strong>2.</strong> Upload your Rate Sheet file with the <br /><a href='/SellerRateSheets/Upload'>Rate Sheet Upload Wizard</a>. You will be given the option to set up a Private Room or leave it public.<br /><br />" +
    "                        <strong>3.</strong> View your uploaded Rate Sheet settings <a href='/SellerRateSheets/'>here</a>.<br /><br />                       " +
    "                    </div>" +
    "                <span class='lb'></span><span class='rb'></span>" +
        "        </div><br class='spacer' />");
    }
    
    function BuyToggle() {
        $("#BuyDiv").slideToggle();
    }
    function SellToggle() {
        $("#SellDiv").slideToggle();
    }

    $(document).ready(function () {
        $("#BuyH1").click(BuyToggle);
        $("#SellH1").click(SellToggle);
    });


//jQueryTools Helpers


    //Yellow box collapse\
    function yellowFillToggle() {
        $("#YFContent").toggle();
        if ($("#YellowFill").attr("class") == "expanded") {
            $("#YellowFill").attr("class", "minimized");
        } else {
            $("#YellowFill").attr("class", "expanded");
        }
    }

    function yellowFillCollapsible() {
        $(document).ready(function () {
            $("#YFheader").click(yellowFillToggle);
        });
    }

    //Tooltips
function Tooltip(elName) {
    var x = $("#" + elName);
    x.tooltip({
        // place tooltip on the right edge     
        position: "center right",
        // a little tweaking of the position     
        offset: [-2, 10],
        // use the built-in fadeIn/fadeOut effect     
        effect: "fade",
        // custom opacity setting     
        opacity: 0.9,
        // use this single tooltip element     
        tip: '.tooltip'
    });
}

    function Tooltips(parent) {
        var x = $("#" + parent + " :input");
        x.tooltip({
            // place tooltip on the right edge     
            position: "center right",
            // a little tweaking of the position     
            offset: [-2, 10],
            // use the built-in fadeIn/fadeOut effect     
            effect: "fade",
            // custom opacity setting     
            opacity: 0.9,
            // use this single tooltip element     
            tip: '.tooltip'
        });
    }

    //Expose
    function highlightElement(parent) {
        $("#" + parent).click(function () {
            // perform exposing for the clicked element         
            $(this).expose({ api: true }).load();
        });
    };

    //Alert bar
    var subCountCookieName = "CClNewSubscriptionCookie";

    function openAlertBar() {

        //Add new Subscription alert
        var count = getSubCount();
        if (count > 0) {
            var pural = "";
            if (count > 1) { pural = "s<strong>(" + count + ")</strong>"; }
            $('#SubContent').html("Click here to manage your new Rate Sheet Subscription" + pural + ".")
        }

        //Check for new subscription versions
        var closed = Boolean($.cookie("CClNewVersionCloseCookie"));
        if(closed == null || closed == undefined){ closed=false; }
        var newVersions = false;
        $.get("/Subscriptions/HasNewVersion", function (data) {
            if (Boolean(data)) { newVersions = Boolean(data);}
            if (newVersions && !closed) { $('#NewSubVers').toggle(); }

            if ((newVersions && !closed) && count > 0) {
                $('#AlertbarFiller').css({ "height": "76px" })
                $('#Alertbar').css({ "margin-top": "-40px" })
            } else {
                $('#AlertbarFiller').css({ "height": "56px" })
                $('#Alertbar').css({ "margin-top": "-20px" })
            }

            if ((newVersions && !closed) || count > 0) {
                $('#AlertbarFiller').slideDown();
                $('#Alertbar').slideDown();
            }
        });
    }

    function closeAlertBar() {
        $('#AlertbarFiller').slideUp();
        $('#Alertbar').slideUp();
        $.cookie("CClNewSubscriptionCookie", 0, { expires: 30, path: '/' });
        if($('#NewSubVers').css("display") != "none"){ $.cookie("CClNewVersionCloseCookie", true, { expires: 0.5, path: '/' }); }
    }

    function getSubCount() {
        var count = 0;
        var oldCount = $.cookie(subCountCookieName);
        if (oldCount != null) {
            count = parseInt(oldCount);
            if (count == NaN) {
                count = 0;
            }
        }
        return count;
    }

    function addSubCount() {
        var count = getSubCount();
        $.cookie(subCountCookieName, (count + 1), { expires: 30, path: '/' });
    }

    /* For dialog builders - easier than escaping them in C# code */


    // Buy grid panel
    function xx() { return; };

    var buyId = "";
    var buyRsId = "";
    var buyRsvId = "";
    var ipError = "";

    function submitBuy() {
        var name = $("#name" + buyId).val();
        if (name == "" || name == null || name == undefined) { $('#ipError').append("<br />Nickname required."); ipError += "<br />Nickname required."; }
        else if (ipError == "<br />Nickname required.") { ipError = ""; }
        var ip = $("#ip" + buyId).val();
        var tp = $("#techPrefix" + buyId).val();
        var action = "/Subscriptions/Create?name=" + name + "&ip=" + ip + "&techPrefix=" + tp + "&rsId=" + buyRsId + "&rsVersion=" + buyRsvId + "&rUrl=" + window.location;
        
        if (ipError.length == 0 || ipError == "" || ipError == null || ipError == undefined) {
            $.post(action, function (data) {
                addSubCount();
                removeSubscribeDiv();
                openAlertBar();
            });
        }
    };
    
    function removeSubscribeDiv() {
        $("#subscribeDiv").remove();
    }

    function Buy(id, rsName, rsId, rsvId) {
        //Set global vars for sumbit
        buyId = id;
        buyRsId = rsId;
        buyRsvId = rsvId;
        
        //remove any previous divs
        removeSubscribeDiv();

        //create html
        if (rsName == null) {
            rsName = "";
            $.getJSON('/PublicRoute/GetRateSheetName/' + rsId, function (data) {
                if (data.rsName.length > 29) { rsName = data.rsName.substring(0, 30) + "" } else { rsName = data.rsName };
                $("#name").val(rsName);
            });
        }
        var rsExpiry = "";
        if (rsvId != null) {
            $.getJSON('/PublicRoute/GetRateSheetCurrentExpiry/' + rsId, function (data) {
                rsExpiry = data.expiry + "";
                $("#expiryDateSpan").html(rsExpiry);
            });
        }

        var htmlString = "<tr style='border-right:1px solid #aaa;'><td colspan='12'><div id='subscribeDiv' style='display:none; z-index=99999; margin-left:7px;' >"
   + "   <div>"
   + "       <div id='GreenFill' style='margin-right:-14px; margin-bottom:8px;'>"
   + "        <span onclick='removeSubscribeDiv()' style='border-left:1px solid #B1D795; padding:1px 5px; font-family:arial; font-weight:bold; font-size:16px; float:right; cursor:pointer;'>X</span>"
   + "        <h1 style='font-size:16px; padding:2px; margin:0; width:872px;'>Create Rate Sheet Subscription:</h1>"
   + "        <div id='ipError' style='color:red;'></div>"
   + "        <table style='width:852px; margin-top:-4px; margin-bottom:-20px;'>"
   + "            <tr>   "
   + "                <td><label>Subscription Nickname:</label></td> "
   + "                <td><input id='name" + id + "' name='name" + id + "' type='text' value='" + rsName + "' /></td>"
   + "                <td><label> &nbsp &nbsp Your Sending IP:</label></td>  "
   + "                <td>"
   + "                    <input onblur='validateIP()' id='ip" + id + "' name='ip" + id + "' type='text' style='width:110px'/></span>"
   + "                </td>"
       + "            <script type='text/javascript'>"
       + "                function validateIP() {"
       + "                    var ipadr = $('#ip"+id+"').val();"
       + "                    $.getJSON('/SellerRateSheets/CheckIp?ip=' + ipadr, function (data) {"
       + "                        $('#ipError').html(data.ErrorMsg); ipError = data.ErrorMsg;"
       + "                    });"
       + "                }"
       + "            </script>"
   + "                <td><label> &nbsp &nbsp Tech Prefix:</label></td> "
   + "                <td><input id='techPrefix" + id + "' name='techPrefix" + id + "' type='text' style='width:100px' /></td>"
   + "            </tr>"
   + "            <tr>"
   + "                <td colspan='5' style='font-size:12px; padding-left:12px; padding-top:4px;'>"
   + "                    • If this Rate Sheet is deleted you will be alerted by email immediately.<br />"
   + "                    • If pricing changes you will receive an alert email to accept the new pricing.<br />"
   + "                    • This Rate Sheet's current Version will expire on: <strong id='expiryDateSpan'></strong><br />"
   + "                    • <a style='color:#2282e3;' href='/Subscriptions/CreateComplex/?rsVersion=" + rsvId + "&rsId=" + rsId + "'><strong>Add to an existing Subscription (Create Complex Subscription)</strong></a>"
   + "                </td>"
   + "                <td>"
   + "                    <input id='sbmtBtn' name='sbmtBtn' style='font-size:14px;' type='button' class='greenBtnLong' value='Subscribe' />"
   + "                </td>"
   + "            </tr>"
   + "        </table>"
   + "        <div class='lb'></div><div class='rb'></div>"
   + "       </div>"
   + "    </div>"
   + "</div></td></tr>";

        //add html
        $("#" + id).after(htmlString);
        $("#sbmtBtn").click(submitBuy)

        //open div panel
        $("#subscribeDiv").slideDown('fast');
    }

    //Rate Sheet Sales Report

    function openSalesReportDialog(id) {
        var srDiv = '<div id="GreenFill" style="width:419px;">' +
    '<div class="lth"></div><div class="rth"></div>' +
    '    <h1>Download RateSheet Sales Report</h1>' +
    '    <table>' +
    '        <tr>' +
    '            <td><label>Start date:</label></td>' +
    '            <td><input id="start" name="start" type="text" /></td>' +
    '        </tr>' +
    '        <tr>' +
    '            <td><label>End date:</label></td>' +
    '            <td><input id="end" name="end" type="text" /></td>' +
    '        </tr>' +
    '    </table>' +
    '<div class="lb"></div><div class="rb"></div>' +
    '</div>' +
    '<script type="text/javascript">    datepickerButtonPanel("start"); datepickerButtonPanel("end");</script>';

        dialogFunc("/SellerRateSheets/DownloadSubscribersSalesReport/" + id, 270, srDiv, "Download");
    }


    //Subscriber Sales Report

    function openRateSheetSalesReportDialog(id) {
        var srDiv = '<div id="GreenFill" style="width:419px;">' +
    '<div class="lth"></div><div class="rth"></div>' +
    '    <h1>Dowload Rate Sheet Sales Report</h1>' +
    '    <table>' +
    '        <tr>' +
    '            <td><label>Start date:</label></td>' +
    '            <td><input id="start" name="start" type="text" /></td>' +
    '        </tr>' +
    '        <tr>' +
    '            <td><label>End date:</label></td>' +
    '            <td><input id="end" name="end" type="text" /></td>' +
    '        </tr>' +
    '    </table>' +
    '<div class="lb"></div><div class="rb"></div>' +
    '</div>' +
    '<script type="text/javascript">    datepickerButtonPanel("start"); datepickerButtonPanel("end");</script>';

        dialogFunc("/SellerRateSheets/DownloadRateSheetSalesReport/" + id, 270, srDiv, "Download");
    }
