﻿var mTotalWeight = 0;
var mTotalCube = 0;

function CalculateTotalWeight(spanWeightID){
    var totalWeight = 0.0;
    var xCurrentWeight;
    var xCurrentQty;
    $('.gridCommoditiesRow').each(function(){
        xCurrentWeight = $(this).find('.gridviewItems_TextBox_Weight').val();
        xCurrentQty = $(this).find('.gridviewItems_TextBox_Quantity').val();
        if (IsNumeric(xCurrentWeight) && IsNumeric(xCurrentQty)){
            totalWeight += parseFloat(xCurrentWeight);// * parseFloat(xCurrentQty);
        }
    });
//    $('.gridviewItems_TextBox_Weight').each(function(){
//        if (IsNumeric($(this).val())) {
//            totalWeight = totalWeight + parseFloat($(this).val());
//        }
//    });
    $('#' + spanWeightID).html(totalWeight.toFixed(2));
    mTotalWeight = totalWeight;
}
function CalculateTotalQuantity(spanQuantityID){
    var totalQuantity = 0.0;
    $('.gridviewItems_TextBox_Quantity').each(function(){
        if (IsNumeric($(this).val())) {
            totalQuantity = totalQuantity + parseFloat($(this).val());
        }
    });
    $('#' + spanQuantityID).html(totalQuantity.toString());
}

function CalculateTotalCube(spanCubeID){
    var totalCube = 0.0;
    $('.gridviewItems_TextBox_Cube').each(function(){
        if (IsNumeric($(this).val())) {
            totalCube = totalCube + parseFloat($(this).val());
        }
    });
    $('#' + spanCubeID).html(totalCube.toFixed(2));
    mTotalCube = totalCube;
}

function CalculateTotalDensity(spanDensityID){
    var thisLength = 0.0;
    var thisWidth = 0.0;
    var thisHeight = 0.0;
    var totalCube = 0.0
    var totalDensity = 0.0;
    
    $('.gridviewItems_TextBox_Density').each(function(){
        var thisObj = $(this).parent().parent();
        
        $(thisObj).find('.gridviewItems_TextBox_Length').each(function(){
            if (IsNumeric($(this).val())) {
                thisLength = parseFloat($(this).val());
            }
        });
        $(thisObj).find('.gridviewItems_TextBox_Width').each(function(){
            if (IsNumeric($(this).val())) {
                thisWidth = parseFloat($(this).val());
            }
        });
        $(thisObj).find('.gridviewItems_TextBox_Height').each(function(){
            if (IsNumeric($(this).val())) {
                thisHeight = parseFloat($(this).val());
            }
        });
    
        if( thisLength > 0 && thisWidth > 0 && thisHeight > 0 ){
            totalCube = totalCube + ((thisLength * thisHeight * thisWidth) / 1728);
        }
        
        thisLength = 0.0;
        thisWidth = 0.0;
        thisHeight = 0.0;
    });
//    $('.gridviewItems_TextBox_Density').each(function(){
//        if (IsNumeric($(this).val())) {
//            totalDensity = totalDensity + parseFloat($(this).val());
//        }
//    });
    totalDensity = (mTotalWeight) / (totalCube);
    $('#' + spanDensityID).html(totalDensity.toFixed(2));
}

function CalculateCube(length, width, height){
    if (IsNumeric(length) && IsNumeric(width) && IsNumeric(height)){
        var cube = 0.0;
        var xLength = parseFloat(length);
        var xWidth = parseFloat(width);
        var xHeight = parseFloat(height);
        cube = (xLength * xWidth * xHeight) / 1728.0;
        return cube;
    } else { return 0.0;}
}

function CalculateDensity(length, width, height, weight, quantity){
    if (IsNumeric(length) && IsNumeric(width) && IsNumeric(height) && IsNumeric(weight) && IsNumeric(quantity)){
        var density = 0.0;
        var xLength = parseFloat(length);
        var xWidth = parseFloat(width);
        var xHeight = parseFloat(height);
        var xWeight = parseFloat(weight);
        var xQuantity = parseFloat(quantity);
        (xWeight == 0 || xLength == 0 || xWidth == 0 || xHeight == 0) ? density = 0 : density = (xWeight * 1728) / (xLength * xWidth * xHeight);
        return density;
    } else { return 0.0;}
}

function IsNumeric(value){
    if (parseFloat(value) == 0 ){
        return true;
    } else if (parseFloat(value)/parseFloat(value) == 1){
        return true;
    }
    return false;
}
function Special_Keydown_Density(event, element){
    var keyCode = (event.which === undefined) ? event.keyCode : event.which;
    var modifiers = (event.altKey || event.ctrlKey || event.shiftKey);
    if ((keyCode == 9 || keyCode == 13) && !modifiers){
        $('#divLineItems').scrollLeft(0);
    }
    return true;
}
function FilterTextbox_Numbers_KeyDown(event, element)
{
    var keyCode = ((event.which === undefined)||(event.which == 0))  ? event.keyCode : event.which;
    if (keyCode == 9){return true;}
    if (keyCode == 13){
        $(":input:text:eq(" + ($(":input:text").index(element) + 1).toString() + ")").focus();
        event.preventDefault();
    }
    var modifiers = (event.altKey || event.ctrlKey || event.shiftKey);
    isNumeric = (keyCode >= 48 /* KeyboardEvent.DOM_VK_0 */ && keyCode <= 57 /* KeyboardEvent.DOM_VK_9 */) ||
                (keyCode == 44 /* Comma */ ) || 
                /*(keyCode >= 96 /* KeyboardEvent.DOM_VK_NUMPAD0  && keyCode <= 105  KeyboardEvent.DOM_VK_NUMPAD9 ) ||*/
                (keyCode == 8 /*Backspace*/) ||
                (keyCode == 46 /*Delete*/) ||
                (keyCode == 110 /*NUMPAD.*/) ||
                (keyCode == 190 /*Keyboard.*/);
    if (modifiers && isNumeric) return false;

    return isNumeric;
}
function FilterTextbox_Money_KeyDown(event, element)
{    
    var keyCode = ((event.which === undefined)||(event.which == 0)) ? event.keyCode : event.which;
    if (keyCode == 9){return true;}
    if (keyCode == 13){
        element.blur();
        $(":input:text:eq(" + ($(":input:text").index(element) + 1).toString() + ")").focus();
        event.preventDefault();
    }
    var modifiers = (event.altKey || event.ctrlKey || event.shiftKey);
    isNumeric = (keyCode >= 48 /* KeyboardEvent.DOM_VK_0 */ && keyCode <= 57 /* KeyboardEvent.DOM_VK_9 */) ||
                (keyCode == 44 /* Comma */ ) || 
                /*(keyCode >= 96 /* KeyboardEvent.DOM_VK_NUMPAD0  && keyCode <= 105  KeyboardEvent.DOM_VK_NUMPAD9 ) ||*/
                (keyCode == 8 /*Backspace*/) ||
                (keyCode == 46 /*Delete*/) ||
                (keyCode == 110 /*NUMPAD.*/) ||
                (keyCode == 190 /*Keyboard.*/);
    if (modifiers && isNumeric) return false;

    return isNumeric;
}
function FilterTextbox_Percent_KeyDown(event, element)
{
    var keyCode = ((event.which === undefined)||(event.which == 0))  ? event.keyCode : event.which;
    if (keyCode == 9){return true;}
    if (keyCode == 13){
        $(":input:text:eq(" + ($(":input:text").index(element) + 1).toString() + ")").focus();
        event.preventDefault();
    }
    var modifiers = (event.altKey || event.ctrlKey || event.shiftKey);
    isNumeric = (keyCode >= 48 /* KeyboardEvent.DOM_VK_0 */ && keyCode <= 57 /* KeyboardEvent.DOM_VK_9 */) ||
                (keyCode == 44 /* Comma */ ) || 
                /*(keyCode >= 96 /* KeyboardEvent.DOM_VK_NUMPAD0  && keyCode <= 105  KeyboardEvent.DOM_VK_NUMPAD9 ) ||*/
                (keyCode == 8 /*Backspace*/) ||
                (keyCode == 46 /*Delete*/) ||
                (keyCode == 110 /*NUMPAD.*/) ||
                (keyCode == 190 /*Keyboard.*/);
    if (modifiers && isNumeric) return false;

    return isNumeric;
}
function FilterTextbox_Pounds_KeyDown(event, element)
{
    var keyCode = ((event.which === undefined)||(event.which == 0)) ? event.keyCode : event.which;
    if (keyCode == 9){return true;}
    if (keyCode == 13){
        $(":input:text:eq(" + ($(":input:text").index(element) + 1).toString() + ")").focus();
        event.preventDefault();
    }
    var modifiers = (event.altKey || event.ctrlKey || event.shiftKey);
    isNumeric = (keyCode >= 48 /* KeyboardEvent.DOM_VK_0 */ && keyCode <= 57 /* KeyboardEvent.DOM_VK_9 */) ||
                (keyCode == 44 /* Comma */ ) || 
                /*(keyCode >= 96 /* KeyboardEvent.DOM_VK_NUMPAD0  && keyCode <= 105  KeyboardEvent.DOM_VK_NUMPAD9 ) ||*/
                (keyCode == 8 /*Backspace*/) ||
                (keyCode == 46 /*Delete*/) ||
                (keyCode == 110 /*NUMPAD.*/) ||
                (keyCode == 190 /*Keyboard.*/);
    if (modifiers && isNumeric) return false;

    return isNumeric;
}
function RemoveChar(element, character, selectAll)
{
    var value = String(element.value);
    var charValue = String(character);
    var selAll = String(selectAll);
    var evalChar = new RegExp(charValue, "g");
    if (charValue == "$")   // $ has special meaning for replace functions
    {
        element.value = value.replace(/\$/g, "");
    }
    else
    {
        element.value = value.replace(evalChar, "");
    }
    
    if (selAll.toLowerCase() == "true")
    {
        element.focus();
        element.select();
    }
}
function SelectTextBox(element)
{
    var value = $(element).val();
    element.value = value.replace(' ', '');
    element.focus();
    element.select();
}

function FormatStringToCurrency(TextValue)
{
    var IsNegative = false;
    TextValue = TextValue.replace(/,/g, "");
    var sArray = new Array();
    sArray = TextValue.split('.');
    if (sArray.length > 2)
    {
        TextValue = TextValue.substring(0, TextValue.indexOf("."));
        alert("Invalid input, please use one period");
        return TextValue;
    }
    TextValue = TextValue.replace("$", "").replace(" ", "");
    if (TextValue.indexOf("(") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace("(", "");
    }
    if (TextValue.indexOf(")") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace(")", "");
    }
    if (TextValue.indexOf("-") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace("-", "");
    }
    if (TextValue.indexOf(".") != -1 )
    {
        var index = TextValue.indexOf(".") + 3;
        TextValue = TextValue + "00";   // This line exists to prevent values like { $80. } from returning
        TextValue = TextValue.substring(0, index);
    }
    else
    {
        TextValue = TextValue + ".00";
    }
    sArray = TextValue.split('.');
    
    if (sArray[0].length > 3)
    {
        var stringCount = Math.floor(sArray[0].length/3);
        var startIndex = sArray[0].length % 3;
        var tempString;
        if (startIndex == 0)
        {
            stringCount = stringCount - 1;
            startIndex = 3;
        }
        tempString = sArray[0].substring(0, startIndex);
        //alert(startIndex);
        for (var counter = 0; counter < stringCount; counter = counter + 1)
        {
            //tempString += TextValue.substring(0, startIndex + (counter*3)) + "," + TextValue.substring(startIndex + (counter*3), TextValue.length -1);
            tempString += "," + sArray[0].substring(((counter * 3) + startIndex), ((counter * 3) + startIndex) + 3);
            //alert("counter: " + counter)
            //alert("," + sArray[0].substring(((counter * 3) + startIndex), ((counter * 3) + startIndex) + 3));
        }
        if (TextValue.indexOf(".") == 0)
            TextValue = "0" + TextValue;
        if (IsNegative)
        {
            TextValue = "($" + tempString + "." + sArray[1] + ")";
        }
        else
        {
            TextValue = "$" + tempString + "." + sArray[1];
        }
    }
    else
    {  
        if (TextValue.indexOf(".") == 0)
            TextValue = "0" + TextValue;      
        if (IsNegative)
        {
            TextValue = "($" + TextValue + ")";
        }
        else
        {
            TextValue = "$" + TextValue;
        }
        
    }
    
    return TextValue;
}

function FormatToCurrency(element)
{
    var TextValue = String(element.value).replace(/,/g, "");
    var useInnerHTML = false;
    var IsNegative = false;
    
    if (TextValue == "undefined") {TextValue = element.innerHTML; useInnerHTML = true;}
    
    if (TextValue == "undefined") // this function has only been tested against text boxes.
    {
        alert("error");
        return;
    }
    var sArray = new Array();
    sArray = TextValue.split('.');
    if (sArray.length > 2)
    {
        element.value = TextValue.substring(0, TextValue.indexOf("."));
        alert("Invalid input, please use one period");
        return;
    }
    TextValue = TextValue.replace("$", "").replace(" ", "");
    if (TextValue.indexOf("(") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace("(", "");
    }
    if (TextValue.indexOf(")") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace(")", "");
    }
    if (TextValue.indexOf("-") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace("-", "");
    }
    if (TextValue.indexOf(".") != -1 )
    {
        var index = TextValue.indexOf(".") + 3;
        TextValue = TextValue + "00";   // This line exists to prevent values like { $80. } from returning
        TextValue = TextValue.substring(0, index);
    }
    else
    {
        TextValue = TextValue + ".00";
    }
    sArray = TextValue.split('.');
    
    if (sArray[0].length > 3)
    {
        var stringCount = Math.floor(sArray[0].length/3);
        var startIndex = sArray[0].length % 3;
        var tempString;
        if (startIndex == 0)
        {
            stringCount = stringCount - 1;
            startIndex = 3;
        }
        tempString = sArray[0].substring(0, startIndex);
        //alert(startIndex);
        for (var counter = 0; counter < stringCount; counter = counter + 1)
        {
            //tempString += TextValue.substring(0, startIndex + (counter*3)) + "," + TextValue.substring(startIndex + (counter*3), TextValue.length -1);
            tempString += "," + sArray[0].substring(((counter * 3) + startIndex), ((counter * 3) + startIndex) + 3);
            //alert("counter: " + counter)
            //alert("," + sArray[0].substring(((counter * 3) + startIndex), ((counter * 3) + startIndex) + 3));
        }
        if (TextValue.indexOf(".") == 0)
            TextValue = "0" + TextValue;
        if (IsNegative)
        {
            TextValue = "($" + tempString + "." + sArray[1] + ")";
        }
        else
        {
            TextValue = "$" + tempString + "." + sArray[1];
        }
    }
    else
    {  
        if (TextValue.indexOf(".") == 0)
            TextValue = "0" + TextValue;      
        if (IsNegative)
        {
            TextValue = "($" + TextValue + ")";
        }
        else
        {
            TextValue = "$" + TextValue;
        }
        
    }
    
    if (useInnerHTML == false) element.value = TextValue; else element.innerHTML = TextValue;
}

function FormatToPercent(element)
{
    var TextValue = String(element.value).replace(/,/g, "");
    var useInnerHTML = false;
    var IsNegative = false;
    
    if (TextValue == "undefined") {TextValue = element.innerHTML; useInnerHTML = true;}
    
    if (TextValue == "undefined") // this function has only been tested against text boxes.
    {
        alert("error");
        return;
    }
    var sArray = new Array();
    sArray = TextValue.split('.');
    if (sArray.length > 2)
    {
        element.value = TextValue.substring(0, TextValue.indexOf("."));
        alert("Invalid input, please use one period");
        return;
    }
    TextValue = TextValue.replace("$", "").replace(" ", "");
    if (TextValue.indexOf("(") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace("(", "");
    }
    if (TextValue.indexOf(")") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace(")", "");
    }
    if (TextValue.indexOf("-") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace("-", "");
    }
    if (TextValue.indexOf(".") != -1 )
    {
        var index = TextValue.indexOf(".") + 3;
        TextValue = TextValue + "00";   // This line exists to prevent values like { $80. } from returning
        TextValue = TextValue.substring(0, index);
    }
    else
    {
        TextValue = TextValue + ".00";
    }
    sArray = TextValue.split('.');
    
    if (sArray[0].length > 3)
    {
        var stringCount = Math.floor(sArray[0].length/3);
        var startIndex = sArray[0].length % 3;
        var tempString;
        if (startIndex == 0)
        {
            stringCount = stringCount - 1;
            startIndex = 3;
        }
        tempString = sArray[0].substring(0, startIndex);
        //alert(startIndex);
        for (var counter = 0; counter < stringCount; counter = counter + 1)
        {
            //tempString += TextValue.substring(0, startIndex + (counter*3)) + "," + TextValue.substring(startIndex + (counter*3), TextValue.length -1);
            tempString += "," + sArray[0].substring(((counter * 3) + startIndex), ((counter * 3) + startIndex) + 3);
            //alert("counter: " + counter)
            //alert("," + sArray[0].substring(((counter * 3) + startIndex), ((counter * 3) + startIndex) + 3));
        }
        if (TextValue.indexOf(".") == 0)
            TextValue = "0" + TextValue;
        if (IsNegative)
        {
            TextValue = "(" + tempString + "." + sArray[1] + ")%";
        }
        else
        {
            TextValue = tempString + "." + sArray[1] + "%";
        }
    }
    else
    {  
        if (TextValue.indexOf(".") == 0)
            TextValue = "0" + TextValue;      
        if (IsNegative)
        {
            TextValue = "(" + TextValue + ")%";
        }
        else
        {
            TextValue = TextValue + "%";
        }
        
    }
    
    if (useInnerHTML == false) element.value = TextValue; else element.innerHTML = TextValue;
}

function FormatToPounds(element)
{
    var TextValue = String(element.value).replace(/,/g, "");
    var useInnerHTML = false;
    var IsNegative = false;
    
    if (TextValue == "undefined") {TextValue = element.innerHTML; useInnerHTML = true;}
    
    if (TextValue == "undefined") // this function has only been tested against text boxes.
    {
        alert("error");
        return;
    }
    var sArray = new Array();
    sArray = TextValue.split('.');
    if (sArray.length > 2)
    {
        element.value = TextValue.substring(0, TextValue.indexOf("."));
        alert("Invalid input, please use one period");
        return;
    }
    TextValue = TextValue.replace("lbs", "").replace(" ", "");
    if (TextValue.indexOf("(") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace("(", "");
    }
    if (TextValue.indexOf(")") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace(")", "");
    }
    if (TextValue.indexOf("-") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace("-", "");
    }
    if (TextValue.indexOf(".") != -1 )
    {
        var index = TextValue.indexOf(".") + 3;
        TextValue = TextValue + "00";   // This line exists to prevent values like { $80. } from returning
        TextValue = TextValue.substring(0, index);
    }
    else
    {
        TextValue = TextValue + ".00";
    }
    sArray = TextValue.split('.');
    
    if (sArray[0].length > 3)
    {
        var stringCount = Math.floor(sArray[0].length/3);
        var startIndex = sArray[0].length % 3;
        var tempString;
        if (startIndex == 0)
        {
            stringCount = stringCount - 1;
            startIndex = 3;
        }
        tempString = sArray[0].substring(0, startIndex);
        //alert(startIndex);
        for (var counter = 0; counter < stringCount; counter = counter + 1)
        {
            //tempString += TextValue.substring(0, startIndex + (counter*3)) + "," + TextValue.substring(startIndex + (counter*3), TextValue.length -1);
            tempString += "," + sArray[0].substring(((counter * 3) + startIndex), ((counter * 3) + startIndex) + 3);
            //alert("counter: " + counter)
            //alert("," + sArray[0].substring(((counter * 3) + startIndex), ((counter * 3) + startIndex) + 3));
        }
        if (TextValue.indexOf(".") == 0)
            TextValue = "0" + TextValue;
        if (IsNegative)
        {
            TextValue = "(" + tempString + "." + sArray[1] + ") lbs";
        }
        else
        {
            TextValue = tempString + "." + sArray[1] + " lbs";
        }
    }
    else
    {  
        if (TextValue.indexOf(".") == 0)
            TextValue = "0" + TextValue;      
        if (IsNegative)
        {
            TextValue = "(" + TextValue + ") lbs";
        }
        else
        {
            TextValue = TextValue + " lbs";
        }
        
    }
    
    if (useInnerHTML == false) element.value = TextValue; else element.innerHTML = TextValue;
}

function FormatToNumber(element, decimalPlaces)
{
    if (decimalPlaces == null){decimalPlaces = 2;}
    var TextValue = String(element.value).replace(/,/g, "");
    var useInnerHTML = false;
    var IsNegative = false;
    var xTrailingZeros = '';
    
    if (TextValue == "undefined") {TextValue = element.innerHTML; useInnerHTML = true;}
    
    if (TextValue == "undefined") // this function has only been tested against text boxes.
    {
        alert("error");
        return;
    }
    TextValue = TextValue.replace("$", "").replace(" ", "");
    TextValue = String( Math.round( parseFloat(TextValue) * Math.pow(10, parseInt(decimalPlaces)) ) / Math.pow(10, parseInt(decimalPlaces)) );
    for(i = 0; i < decimalPlaces; i++){
        xTrailingZeros += '0';
    }
    
    var sArray = new Array();
    sArray = TextValue.split('.');
    if (sArray.length > 2)
    {
        element.value = TextValue.substring(0, TextValue.indexOf("."));
        alert("Invalid input, please use one decimal");
        return;
    }
    if (TextValue.indexOf("(") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace("(", "");
    }
    if (TextValue.indexOf(")") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace(")", "");
    }
    if (TextValue.indexOf("-") != -1)
    {
        IsNegative = true;
        TextValue = TextValue.replace("-", "");
    }
    if (TextValue.indexOf(".") != -1 )
    {
        var index = TextValue.indexOf(".") + 3;
        TextValue = TextValue + xTrailingZeros;   // This line exists to prevent values like { $80. } from returning
        TextValue = TextValue.substring(0, index);
    }
    else
    {
        if(xTrailingZeros.toString().length > 0)
            TextValue = TextValue + "." + xTrailingZeros;
    }
    sArray = TextValue.split('.');
    
    if (sArray[0].length > 3)
    {
        var stringCount = Math.floor(sArray[0].length/3);
        var startIndex = sArray[0].length % 3;
        var tempString;
        if (startIndex == 0)
        {
            stringCount = stringCount - 1;
            startIndex = 3;
        }
        tempString = sArray[0].substring(0, startIndex);
        //alert(startIndex);
        for (var counter = 0; counter < stringCount; counter = counter + 1)
        {
            //tempString += TextValue.substring(0, startIndex + (counter*3)) + "," + TextValue.substring(startIndex + (counter*3), TextValue.length -1);
            tempString += "," + sArray[0].substring(((counter * 3) + startIndex), ((counter * 3) + startIndex) + 3);
            //alert("counter: " + counter)
            //alert("," + sArray[0].substring(((counter * 3) + startIndex), ((counter * 3) + startIndex) + 3));
        }
        if (TextValue.indexOf(".") == 0)
            TextValue = "0" + TextValue;
        if (IsNegative)
        {
            if(xTrailingZeros.toString().length > 0)
                TextValue = "- " + tempString + "." + sArray[1] + "";
            else
                TextValue = "- " + tempString;
        }
        else
        {
            if(xTrailingZeros.toString().length > 0)
                TextValue = "" + tempString + "." + sArray[1];
            else
                TextValue = "" + tempString;
        }
    }
    else
    {  
        if (TextValue.indexOf(".") == 0)
            TextValue = "0" + TextValue;      
        if (IsNegative)
        {
            TextValue = "- " + TextValue + "";
        }
        else
        {
            TextValue = "" + TextValue;
        }
        
    }
    
    if (useInnerHTML == false) element.value = TextValue; else element.innerHTML = TextValue;
}

function getParameterByName( 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 decodeURIComponent(results[1].replace(/\+/g, " "));
}

function SetSearchText(objectID, text)
{
    if (objectID.toString().indexOf('#') == -1)
        objectID = '#' + objectID;
    $(objectID).val(text);
    $(objectID).css('color', '#cccccc');
    $(objectID).bind('focus', function(){
        if ($(objectID).val() == text)
        {
            $(objectID).val('');
            $(objectID).css('color', '#000000');
        }
        $(objectID).select();
    }).bind('blur', function(){
        if ($(objectID).val().toString().trim() == '')
        {
            $(objectID).val(text);
            $(objectID).css('color', '#cccccc');
        }
    });
}
    var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
function ShowContactDiv(divID)
{
    $('#' + divID).stop(false, true).show('expand');//, function(){
}
function HideContactDiv(divID)
{
    $('#' + divID).stop(false, true).hide("collapse");
}
function FormatPhone(inputString)
{
    inputString = inputString.replace(/\)/g, '').replace(/-/g, '').replace(/ /g, '').replace(/\)/g, '');
    
    if( IsNumeric(inputString) && inputString.length == 10 ){
        return '(' + inputString.substring(0, 3) + ') ' + inputString.substring(2, 5) + '-' + inputString.substring(5, 9)
    }else{
        return 'Invalid';
    }
}

function CanDeleteContact(element, type){
    if( type == 1 ){
        if( $(element).parents('.contactContainer').find('.IsDefaultRadioButton').find('input:radio').is(':checked') ){
            alert('You cannot delete the default contact.');
            return false;
        }else{
            return confirm('Are you sure you want to delete this Contact?');
        }
    }else if( type == 0 ){
        if( $(element).parents('.contactContainer').find('.IsDefaultRadioButton').find('input:radio').is(':checked') ){
            alert('You cannot delete the default contact.');
            return false;
        }else{
            return true;
        }
    }
    return true;
}

(function( $ ){

    $.fn.seedBarGraph = function( options ) {  

        
        var settings = $.extend( {
            sets                : [],
            setIndex            : 0,
            editable            : true,
            saveID              : 'hdnSets',
            maxEditColumnSize   : 25
        }, options);

        return this.each(function() {        
            var subTitle = '';
            var index = 10;
            var maxIndex = settings.sets[settings.setIndex].States.length - 1;
            var holder = this;
            
            if(index > settings.sets[settings.setIndex].States.length)
                index = settings.sets[settings.setIndex].States.length;

            $(this).removeClass('ui-widget').removeClass('ui-graph').children().remove();
            $(this).addClass('ui-widget').addClass('ui-graph');
            
            var thisSet = $('<div class="ui-state-highlight ui-corner-all ui-graph-set"></div>');
            $(this).append(thisSet);
            $(thisSet).append('<center><span class="ui-graph-title">' + settings.sets[settings.setIndex].Title + '</span></center>');
            $(thisSet).append('<center><span class="ui-graph-subtitle">' + settings.sets[settings.setIndex].TenSubTitle + '</span></center>');
            $(thisSet).append('<br />');
            
            for(var i = 0; i < index; i++){
                var thisRow = $('<div class="ui-graph-row"></div>');
                $(thisSet).append(thisRow);
                $(thisRow).append($('<div class="ui-graph-row-label">' + settings.sets[settings.setIndex].States[i].Name + '</div>'));
                var thisDataPoint = $('<div class="ui-graph-row-datapoint"></div>');
                var thisProgressBar = $('<div class="progressBar"></div>');
                $(thisRow).append(thisDataPoint);
                $(thisDataPoint).append(thisProgressBar);
                $(thisProgressBar).progressbar({value:settings.sets[settings.setIndex].States[i].Value});
            }
            
            var showAllDialog = $('<div></div>');
            $(document).append(showAllDialog);
                
            var showAllButton = $('<a href="javascript:void(0);" class="ui-icon ui-icon-newwin ui-graph-tool-newwin"></a>');
            $(this).append(showAllButton);
            $(showAllButton).bind('click', function(){
                $(showAllDialog).dialog('open');
            });
            
            thisSet = $('<div class="ui-state-highlight ui-corner-all ui-graph-set"></div>');
            $(showAllDialog).append(thisSet);
            $(thisSet).append('<center><span class="ui-graph-title">' + settings.sets[settings.setIndex].Title + '</span></center>');
            $(thisSet).append('<center><span class="ui-graph-subtitle">' + settings.sets[settings.setIndex].TenSubTitle + '</span></center>');
            $(thisSet).append('<br />');
            
            index = settings.sets[settings.setIndex].States.length;
            for(var i = 0; i < index; i++){
                var thisRow = $('<div class="ui-graph-row"></div>');
                $(thisSet).append(thisRow);
                $(thisRow).append($('<div class="ui-graph-row-label">' + settings.sets[settings.setIndex].States[i].Name + '</div>'));
                var thisDataPoint = $('<div class="ui-graph-row-datapoint"></div>');
                var thisProgressBar = $('<div class="progressBar"></div>');
                $(thisRow).append(thisDataPoint);
                $(thisDataPoint).append(thisProgressBar);
                $(thisProgressBar).progressbar({value:settings.sets[settings.setIndex].States[i].Value});
            }
            
            $(thisSet).find('.ui-progressbar').css('height', '10px');
            
            var xHeight = index * 15 + 169;
            var xWidth = 362;
            if( xHeight > 664 ){
                xHeight = 664;
                xWidth = 362 + 17;
            }
            
            $(showAllDialog).dialog({
                modal       :true, 
                autoOpen    :false, 
                width       :xWidth, 
                height      :xHeight, 
                closeOnEscape:true,
                buttons     :{
			        "Close": function() {
				        $( this ).dialog( "close" );
			        }
			    }
			});
            
            if( settings.editable ){
                var editButton = $('<a href="javascript:void(0);" class="ui-icon ui-icon-pencil ui-graph-tool-pencil"></a>');
                $(this).append(editButton);
                
                var editDialog = $('<div></div>');
                $(document).append(editDialog);
                
                $(editButton).bind('click', function(){
                    $(editDialog).dialog('open');
                });
                
                var counter = 0;
                var columns = Math.ceil((maxIndex + 1) / settings.maxEditColumnSize);
                var rows = Math.ceil((maxIndex + 1) / columns);
                var divTable = $('<table></table>');
                $(editDialog).append(divTable);
                var width = columns * 115 * 2 + (Math.abs(columns - 1) * 25);
                var height = 100 + rows * 22;
                var rowArray = new Array();
                var tbArray = new Array(); /*array to hold the textboxes*/
                
                /*build each row for the edit table, this will enable us to keep the values in order from top to bottom, as apposed to left to right*/
                for( var i = 0; i < rows; i++ ){
                    rowArray[i] = $('<tr style="display:table-row;margin:1px;"></tr>');
                    $(divTable).append(rowArray[i]);
                }
                
                for(var i = 0; i < columns; i++){
                    if( counter > maxIndex )
                        break;
                    
                    for(var x = 0; x < rows; x++){
                        if( counter > maxIndex )
                            break;
                        
                        var paddingLeft = 0;
                        if (i > 0)
                            paddingLeft = 25;
                        $(rowArray[x]).append($('<td style="display:table-cell;padding:1px;min-width:100px;padding-left:' + paddingLeft.toString() + 'px;">' + settings.sets[settings.setIndex].States[counter].Name + '</td>'));
                        tbArray[counter] = $('<input type="text" id="t:' + counter.toString() + '" style="width:75px;text-align:right;border: 1px solid #ABADB3;" value="' + settings.sets[settings.setIndex].States[counter].Value + '" class="statesTextBox" />');
                        $(rowArray[x]).append($('<td style="display:table-cell;padding:1px;"></td>').append(tbArray[counter]));
                        $(rowArray[x]).append($('<td>%</td>'));
                        counter++;
                    }
                }
                
                
                $(divTable).find('.statesTextBox').each(function(){FormatToNumber(this, 2);});
                $(divTable).find('.statesTextBox').bind('keypress', function(e){return FilterTextbox_Numbers_KeyDown(e, this);}).bind('blur', function(){FormatToNumber(this, 2);}).bind('focus click', function(){RemoveChar(this, ',', 'true');}).bind('mouseup', function(){return false;});
                
                $(editDialog).dialog({
                    modal       :true, 
                    autoOpen    :false, 
                    width       :width, 
                    height      :height, 
                    closeOnEscape:true,
                    buttons     :{
				        "Save": function() {
				            var csvSets = '';
				            for( var i  = 0; i < settings.sets[settings.setIndex].States.length; i++ ){
				                settings.sets[settings.setIndex].States[i].Value = parseFloat( $(tbArray[i]).val() );
				                csvSets = csvSets + settings.sets[settings.setIndex].States[i].Name + ',';
				                csvSets = csvSets + settings.sets[settings.setIndex].States[i].Value + '§';
				            }
				            $('#' + settings.saveID).val(csvSets);
			                $(holder).html('').children().each().remove();
			                $(holder).removeClass('ui-widget').removeClass('ui-graph');
			                $(editDialog).remove();
			                $(showAllDialog).remove();
				            $(holder).seedBarGraph(settings);
					        $( this ).dialog( "close" );
				        },
				        Cancel: function() {
					        $( this ).dialog( "close" );
				        }
				    }
				});
				
				/*Set an initial save state - only if edit is true*/
			    var csvSets = '';
                for( var i  = 0; i < settings.sets[settings.setIndex].States.length; i++ ){
                    csvSets = csvSets + settings.sets[settings.setIndex].States[i].Name + ',';
                    csvSets = csvSets + settings.sets[settings.setIndex].States[i].Value + '§';
                }
                $('#' + settings.saveID).val(csvSets);
            }
        });

    };
})( jQuery );
