// JScript File

function charCounter(obj, e, spnCounterID, spnCounterID1) {

    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    /*if ((key==null) || (key==0) || (key==8) || 
    (key==9) || (key==13) || (key==27) )
    return true;
    */

    str = obj.value; // + keychar;


    remaining = 300 - str.length;
    spn = document.getElementById(spnCounterID);
    spn.innerHTML = "" + remaining + " characters remaining.";
    /*if(str.length < 7)
    {
    spn1=document.getElementById(spnCounterID1);
    spn1.innerHTML = ""+ "Please enter 7 characters minimum.";      
    }
    else
    {
    spn1.innerHTML = "";      
    }*/

    if (str.length >= 300) {
        obj.value = str.substr(0, 300);

        if ((key == null) || (key == 0) || (key == 8) ||
	    (key == 9) || (key == 13) || (key == 27))
            return true;
        else return false;


    }

}


function charCounterTot(obj, e, spnCounterID, spnCounterID1, totChar) {

    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    str = obj.value; // + keychar;

    remaining = totChar - str.length;
    spn = document.getElementById(spnCounterID);
    spn.innerHTML = "" + remaining + " Characters Remaining.";


    if (str.length >= totChar) {
        obj.value = str.substr(0, totChar);

        if ((key == null) || (key == 0) || (key == 8) ||
	    (key == 9) || (key == 13) || (key == 27))
            return true;
        else return false;


    }

}


function countChar(fieldId, cntfieldId, maxLength, optValue) {
    var field = document.getElementById(fieldId);
    var cntfield = document.getElementById(cntfieldId);
    if (field.value.length > maxLength) {
        field.value = field.value.substring(0, maxLength);
    }
    cntfield.innerHTML = 'Character Count - ' + field.value.length;

}

// General Functions

function isNumberKey(evt, str, obj, maxVal, maxLength)       //Function to check for Numeric Values Only
{

    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
        return false;
    else
        if ((charCode == 46) && (str.indexOf(".") != -1))
        return false;
    else
        if (typeof (obj) != 'undefined') {
        if (parseFloat(obj.value) > maxVal) {
            return false;
        }
        else
            if (typeof (maxLength) != 'undefined') {
            if (obj.value.length > maxLength)
                return false;
        }
    }


    return true;
}

//  Rounding off for Numbers

function roundOff(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()

    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {

        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0

        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }

    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length

    if (pad_total > 0) {

        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++)
            value_string += "0"
    }
    return value_string
}

// Trim using Regex
String.prototype.trim = function() {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

// Text Masking functions begins

// Javascript Numeric EditMask

// simple RegEx patterns used.

var reOneOrMoreDigits = /[\d+]/;

var reNoDigits = /[^\d]/gi;

function doMask(textBox) {

    var keyCode = event.which ? event.which : event.keyCode;
    // enter, backspace, delete and tab keys are allowed thru
    if (keyCode == 13 || keyCode == 8 || keyCode == 9 || keyCode == 46)
        return true;
    // get character from keyCode....dealing with the "Numeric KeyPad" 
    // keyCodes so that it can be used

    var keyCharacter = cleanKeyCode(keyCode);

    // grab the textBox value and the mask

    var val = textBox.value;

    var mask = textBox.mask;

    // simple Regex to check if key is a digit


    if (reOneOrMoreDigits.test(keyCharacter) == false)


        return false;





    // get value minus any masking by removing all non-numerics


    val = val.replace(reNoDigits, '');





    // add current keystroke


    val += keyCharacter;





    // mask it...val holds the existing TextBox.value + the current keystroke


    textBox.value = val.maskValue(mask);





    setCaretAtEnd(textBox);





    return false;


}


// puts starting chars in field


function onFocusMask(textBox) {


    var val = textBox.value;


    var mask = textBox.mask;


    if (val.length == 0 || val == null) {


        var i = mask.indexOf('#');


        textBox.value = mask.substring(0, i);


    }


    setCaretAtEnd(textBox);


    // set just in case.


    textBox.maxlength = mask.length;


}


// blank field if no digits entered


function onBlurMask(textBox) {


    var val = textBox.value;


    // if no digits....nada entered.....blank it.


    if (reOneOrMoreDigits.test(val) == false) {


        textBox.value = '';


    }


}


String.prototype.maskValue = function(mask) {


    var retVal = mask;


    var val = this;





    //loop thru mask and replace #'s with current value one at a time


    // better way of doing this ???


    for (var i = 0; i < val.length; i++) {


        retVal = retVal.replace(/#/i, val.charAt(i));


    }


    // get rid of rest of #'s


    retVal = retVal.replace(/#/gi, "");


    return retVal;


}


// The Numeric KeyPad returns keyCodes that ain't all that workable.


//


// ie: KeyPad '1' returns keyCode 97 which String.fromCharCode converts to an 'a'.


//


// This cheesy way allows the Numeric KeyPad to be used


function cleanKeyCode(key) {


    switch (key) {


        case 96: return "0"; break;


        case 97: return "1"; break;


        case 98: return "2"; break;


        case 99: return "3"; break;


        case 100: return "4"; break;


        case 101: return "5"; break;


        case 102: return "6"; break;


        case 103: return "7"; break;


        case 104: return "8"; break;


        case 105: return "9"; break;


        default: return String.fromCharCode(key); break;


    }


}


function setCaretAtEnd(field) {


    if (field.createTextRange) {


        var r = field.createTextRange();


        r.moveStart('character', field.value.length);


        r.collapse();


        r.select();


    }


}

// Text Masking functions Ends

//Function to reflect change in one dropdown list to another dropdownlist
function ddlChange(obj1Id, obj2Id) {
    var ddlSource = document.getElementById(obj1Id);
    var ddlTarget = document.getElementById(obj2Id);
    index = ddlSource.selectedIndex;
    ddlTarget.selectedIndex = index;
    //var index = document.all.ddlbVariables.selectedIndex;
}
//Function to reflect change in one textbox to another textbox
function copyText(txt1Id, txt2Id) {
    var txtSource = document.getElementById(txt1Id);
    var txtTarget = document.getElementById(txt2Id);

    txtTarget.value = txtSource.value;
}
//Function to close a popup and refresh the parent window
function refreshParent() {
    window.opener.location.href = window.opener.location.href;

    if (window.opener.progressWindow) {
        window.opener.progressWindow.close()
    }
    window.close();
}

//Function to refresh the parent window without close
function refreshParentWithoutClose() {
    window.opener.location.href = window.opener.location.href;

    if (window.opener.progressWindow) {
        window.opener.progressWindow.close()
    }
    //window.close();
}


//Function to validate email address
function IsValidEmail(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

    if (reg.test(email) == false) {
        //alert('Invalid Email Address');
        return false;
    }
}

// Function to check To and From values DDL
function checkToValue(ddlFromId, objDdlTo) {

    var ddlTo = objDdlTo;
    var ddlFrom = document.getElementById(ddlFromId);


    //alert(ddlFrom.options[ddlFrom.selectedIndex].value + '----' + ddlTo.options[ddlTo.selectedIndex].value );
    if (ddlTo.selectedIndex > 0) {
        if (parseFloat(ddlTo.options[ddlTo.selectedIndex].value) <= parseFloat(ddlFrom.options[ddlFrom.selectedIndex].value)) {
            alert('Invalid Range');
            ddlTo.selectedIndex = 0;
            ddlTo.focus();
        }
    }

}

function checkFromValue(ddlToId, objDdlFrom) {
    var ddlFrom = objDdlFrom;
    var ddlTo = document.getElementById(ddlToId);


    //alert(ddlFrom.options[ddlFrom.selectedIndex].value + '----' + ddlTo.options[ddlTo.selectedIndex].value );
    if ((ddlFrom.selectedIndex > 0) && (ddlTo.selectedIndex > 0)) {
        var fromValue = parseFloat(ddlFrom.options[ddlFrom.selectedIndex].value);
        var toValue = parseFloat(ddlTo.options[ddlTo.selectedIndex].value);
        if (fromValue >= toValue) {
            //                alert('Invalid Range');
            //                ddlFrom.selectedIndex = 0;
            ddlTo.selectedIndex = 0;
            ddlFrom.focus();
        }
    }

}

function getTxtStartDateId(txtEndDateId) {
    return (txtEndDateId.replace("tbNewSaleEndDate", "tbNewSaleStartDate"));
}



/*  Image Selector Scripts
Deepak Kothari
Aug 07, 2008
*/
function GetE(elementId) {
    return document.getElementById(elementId);
}
function applyData() {
    //            window.opener.setArticleHTML(previewData)
    //            window.close() ;

    if (window.opener && !window.opener.closed) {

        var imPath = GetE('imselect').src;
        var alt = GetE('txtAlt').value;
        var width = getWidth();
        var height = getHeight();

        var hSpIndx = GetE('ddlHSpace').selectedIndex;
        var hSpace = GetE('ddlHSpace').options[hSpIndx].text;

        var vSpIndx = GetE('ddlVSpace').selectedIndex;
        var vSpace = GetE('ddlVSpace').options[vSpIndx].text;


        var border = GetE('imselect').style.border;

        var indx = GetE('ddlalign').selectedIndex;
        var align = GetE('ddlalign').options[indx].text;

        window.opener.setImagePath(imPath, alt, width, height, hSpace, vSpace, border, align);    //setImagePath(imPath,alt,width,height,hSpace,vSpace,border,align)
    }
    else {
        alert("Parent window is closed. Please re-open this window from Parent Window.");
    }
    window.close();
}


function calcProportion() {
    if (chkUnit() == 0)
        proportion = (document.all.txtwidth.value * 72) / (document.all.txtheight.value * 72);
    else
        proportion = document.all.txtwidth.value / document.all.txtheight.value;

}

function checkHeight() {
    var imgPrev = GetE('imselect');
    var chkProportion = GetE('chkProportion');
    var txtWidth = GetE('txtwidth');

    if (chkProportion.checked) {
        if (txtWidth.value.length > 0)
            document.all.txtheight.value = txtWidth.value / proportion;
        else
            document.all.txtheight.value = ""; ;
    }
    updatePreview();
}

function checkWidth() {
    var imgPrev = GetE('imselect');
    var chkProportion = GetE('chkProportion');
    var txtHeight = GetE('txtheight');

    if (chkProportion.checked) {
        if (txtHeight.value.length > 0)
            document.all.txtwidth.value = txtHeight.value * proportion;
        else
            document.all.txtwidth.value = "";
    }
    updatePreview();
}

function showPreview() {

    var sel = document.getElementById("lstImages");
    url = sel.options[sel.selectedIndex].value;
    var img = new Image();  //var variableName = new Image();
    img.src = url;

    document.all['divPreview'].style.display = "block";
    var imgPrev = document.getElementById("imselect");
    imgPrev.style.display = "block";
    imgPrev.src = url;
    document.all.txtheight.value = roundOff(valueInUnit(img.height), 2);
    document.all.txtwidth.value = roundOff(valueInUnit(img.width), 2);
    imgPrev.width = img.width;
    imgPrev.height = img.height;

}

function updatePreview() {
    var imgPrev = GetE("imselect");
    var hSpIndx = GetE('ddlHSpace').selectedIndex;
    var hSpace = GetE('ddlHSpace').options[hSpIndx].text;

    var vSpIndx = GetE('ddlVSpace').selectedIndex;
    var vSpace = GetE('ddlVSpace').options[vSpIndx].text;
    imgPrev.hspace = hSpace;
    imgPrev.vspace = vSpace;
    imgPrev.width = getWidth();
    imgPrev.height = getHeight();

    var ddlBorderSize = GetE("ddlBorderSize");
    var ddlBorderStyle = GetE('ddlBorderStyle');
    var ddlBorderColor = GetE('cboColor');

    var bColor = ddlBorderColor.options[ddlBorderColor.selectedIndex].value;

    var bSize = ddlBorderSize.options[ddlBorderSize.selectedIndex].value;
    var bStyle = ddlBorderStyle.options[ddlBorderStyle.selectedIndex].value;
    //WebUserControl11_cboColor

    var finalBorder = bSize + 'px ' + bStyle + ' ' + bColor;     //' #ff0000';
    imgPrev.style.border = finalBorder.toLowerCase();

    var sel = GetE("ddlalign");
    //pnlPreview

    //                    
    //alert(pnlPreview.getElementById('divPreview').align);
    if (sel.options[sel.selectedIndex].value == 'center') {

        imgPrev.className = 'center';
    }
    else {
        //                      var pnlPreview = document.getElementById('pnlPreview')
        //                      pnlPreview.getElementById('divPreview').align = sel.options[sel.selectedIndex].value;

        imgPrev.align = sel.options[sel.selectedIndex].value;
    }
    sel.options[sel.selectedIndex].value = '';


    //                    alert(sel.options[sel.selectedIndex].value);
    //                    imgPrev.align = sel.options[sel.selectedIndex].value;
    //                    alert(imgPrev.align);
}

function isNumberKey(evt, str) {

    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
        return false;
    else
        if ((charCode == 46) && (str.indexOf(".") != -1))
        return false;

    return true;
}

function valueInUnit(val) {
    var ddlUnt = document.getElementById('ddlUnit');
    //var unit = ddlUnt.options[ddlUnt.selectedIndex].value;
    var unitIndx = ddlUnt.selectedIndex;

    if (unitIndx == 0)
        return (val / 72);
    else
        return (val);

}
function chkUnit() {
    var ddlUnt = document.getElementById('ddlUnit');
    var unitIndx = ddlUnt.selectedIndex;
    return (unitIndx);
}

function getWidth() {
    var txtWidth = GetE('txtwidth');
    var wdth;
    if (chkUnit() == 0)
        wdth = txtWidth.value * 72;
    else
        wdth = txtWidth.value;
    return (wdth);
}

function getHeight() {
    //vat txtHeight = GetE('txtHeight');
    var hgt;
    if (chkUnit() == 0)
        hgt = GetE('txtheight').value * 72;
    else
        hgt = GetE('txtheight').value;
    return (hgt);
}
function setPresetValues() {
    var ddlPreset = GetE('ddlPresets');
    var presetIndx = ddlPreset.selectedIndex;
    switch (presetIndx) {
        case 0:
            var sel = document.getElementById("lstImages");
            url = sel.options[sel.selectedIndex].value;
            var img = new Image();  //var variableName = new Image();
            img.src = url;
            setWidthHeight(img.width, img.height);
            break;
        case 1:
            setWidthHeight(100, 100);
            break;

        case 2:
            setWidthHeight(300, 300);
            break;

        case 3:
            setWidthHeight(432, 432);
            break;

        case 4:
            setWidthHeight(273, 154);
            break;

        case 5:
            setWidthHeight(160, 130);
            break;

        case 6:
            setWidthHeight(495, 264);
            break;

        case 7:
            setWidthHeight(195, 216);
            break;

    }
    updatePreview();
}

function setWidthHeight(width, height) {
    var txtWidth = GetE('txtwidth');
    var txtHeight = GetE('txtheight');
    txtWidth.value = valueInUnit(width);
    txtHeight.value = valueInUnit(height);
}

function getFinalHTMLString() {
    var strHTML;
    strHTML = '<input type="Image" id="img" ';

}
// Image Selector Scripts Ends

//Function for Tabbed article pages 
// Deepak Kothari 
// Oct 08, 2008
function showDiv(obj) {

    var parentTagDiv = document.getElementById('ctl00_ContentCustomerMain_Articles_Tab_AboutUs');
    var tagButtons = parentTagDiv.getElementsByTagName('A');
    for (i = 0; i < tagButtons.length; i++)
        tagButtons[i].className = '';
    obj.className = 'selected';
    obj.blur();
    //Showing the required DIV
    var parentDiv = document.getElementById('ctl00_ContentCustomerMain_Articles_divContents');

    var tagItems = parentDiv.getElementsByTagName('div');

    for (i = 0; i < tagItems.length; i++)
        if (tagItems[i].id)
        if (tagItems[i].id.indexOf('div~') != -1)
        tagItems[i].style.display = 'none';

    document.getElementById('div~' + obj.id).style.display = 'block';
    checkBodyHeight();
}

// Function to detect mouse in and mouse out for an Element

//since mouseenter & mouseleave are only supported in IE, this object helps to
// determine if the mouse is entering or leaving an element
//landmark: did the mouse enter or leave this "landmark" element? Was the event fired from within this element?
//usage: var mbc = new MouseBoundaryCrossing(mouse_event, landmark);
function MouseBoundaryCrossing(evt, landmark) {
    evt = evt || window.event;

    var eventType = evt.type;

    this.inLandmark = false;
    this.leftLandmark = false;
    this.enteredLandmark = false;

    if (eventType == "mouseout") {
        this.toElement = evt.relatedTarget || evt.toElement;
        this.fromElement = evt.target || evt.srcElement;
    }
    else if (eventType == "mouseover") {
        this.toElement = evt.target || evt.srcElement;
        this.fromElement = evt.relatedTarget || evt.fromElement;
    }
    else throw (new Error("Event type \"" + eventType + "\" is irrelevant")); //irrelevant event type

    //target is unknown
    //this seems to happen on the mouseover event when the mouse is already inside the element when the page loads and
    // the mouse is moved: fromElement is undefined
    if (!this.toElement || !this.fromElement) throw (new Error("Event target(s) undefined"));

    //determine whether from-element is inside or outside of landmark (i.e., does tmpFrom == the landmark or the document?)
    var tmpFrom = this.fromElement;
    while (tmpFrom.nodeType == 1) //while tmpFrom is an element node
    {
        if (tmpFrom == landmark) break;
        tmpFrom = tmpFrom.parentNode;
    }

    //determine whether to-element is inside or outside of landmark (i.e., does tmpTo == the landmark or the document?)
    var tmpTo = this.toElement;
    while (tmpTo.nodeType == 1) //while tmpTo is an element node
    {
        if (tmpTo == landmark) break;
        tmpTo = tmpTo.parentNode;
    }

    if (tmpFrom == landmark && tmpTo == landmark) this.inLandmark = true; //mouse is inside landmark; didn't enter or leave
    else if (tmpFrom == landmark && tmpTo != landmark) //mouse left landmark
    {
        this.leftLandmark = true;
        this.inLandmark = (eventType == "mouseout"); //mouseout: currently inside landmark, but leaving now
        //mouseover: currently outside of landmark; just left
    }
    else if (tmpFrom != landmark && tmpTo == landmark) //mouse entered landmark
    {

        this.enteredLandmark = true;

        this.inLandmark = (eventType == "mouseover"); //mouseover: currently inside landmark; just entered

        //mouseout: currently outside of landmark, but entering now

    }

    //else //mouse is outside of landmark; didn't enter or leave

}

//Function to set Page size in hidden text from Dropdown
function SetDDLValue(obj, hdnId, hdnPageNumId) {
    //alert(obj.options[obj.selectedIndex].value);

    document.getElementById(hdnId).value = obj.options[obj.selectedIndex].value;
    document.getElementById(hdnPageNumId).value = 1;


}
//function for product upload
function chkBoxChange(obj) {
    var chkBox = document.getElementById(obj.id);
    var visibleItems = document.getElementById('ctl00_ctl00_ContentCustomerMain_AdminContentPlaceHolder_hdnVisibleItems').value;
    var limitOfVisibleItem = document.getElementById('ctl00_ctl00_ContentCustomerMain_AdminContentPlaceHolder_hdnLimitOfVisibleItems').value;
    if (chkBox.checked == true) {
        visibleItems = parseInt(visibleItems) + 1;
    }
    else {
        visibleItems = parseInt(visibleItems) - 1;
    }


    if (parseInt(visibleItems) > parseInt(limitOfVisibleItem)) {
        alert("You can only show " + parseInt(limitOfVisibleItem) + " items at a time. If you want to show this item then please block some other item");
        document.getElementById(obj.id).checked = false;
        visibleItems = parseInt(visibleItems) - 1;
    }
    document.getElementById('ctl00_ctl00_ContentCustomerMain_AdminContentPlaceHolder_hdnVisibleItems').value = visibleItems;

    //alert('Message from script' + visibleItems + ' limit ' + limitOfVisibleItem);
}
//function chkBoxChange(obj)
//{
//    alter('TAasdfasdfsad'+ obj);
//    var chkBox = document.getElementById(obj);        
//    var visibleItems = document.getElementById("<%= hdnVisibleItems.ClientID %>").value;
//    var limitOfVisibleItem = document.getElementById("<%= hdnLimitOfVisibleItems.ClientID %>").value;
//    if(chkBox.checked == true)
//        visibleItems = parseInt(visibleItems) +1;
//        
//    if(parseInt(visibleItems) > parseInt(limitOfVisibleItem))
//    {
//        alert("You can only show "+ parseInt(limitOfVisibleItem)+ " items at a time. If you want to show this item then please block some other item");
//        document.getElementById(obj.id).checked = false;
//    }
//alert(chkBox + " abc " +visibleItems);
//}

function checkBodyHeight() {
    var ht = document.body.clientHeight;
    var leftmn = document.getElementById('ctl00_ContentCustomerMain_mnLeftMenu_divMain1');
    var mainDiv = document.getElementById('divContent');
    if (ht < 590) {


        if (leftmn != 'undefined' && leftmn != null) {
            //alert('Increasing left menu');
            leftmn.style.height = '400px';
        }
        else {
            //alert('No Left menu exists');
            mainDiv.style.height = '400px';
        }
    }
    else
        mainDiv.style.height = '';
}
