﻿$(document).ready
	(
		function () {
		    //InitializeGridControls();
		    DirtyField();
		    AjaxPicker();
		    SumField();
		    NumericText();
		    Textbox();
		}
	);

function Textbox() {
    $("input[type='text']").live("click", function () {
        $(this).select();
    });
}

function AjaxPicker() {

    $('.AjaxSelect').live("focus", function () {
        var context = new Object;
        if (window.OnAjaxPickerLoad) {
            OnAjaxPickerLoad(context);
        }
        if ($("option", this).size() <= 2) {
            var ctrl = this;
            $("option:not(:selected)", this).remove();
            $.ajax({
                type: "POST",
                datatype: "json",
                contentType: 'application/json; charset=utf-8',
                data: "{\"context\": " + JSON.stringify(context) + "}",
                async: false,
                url: $(ctrl).attr("Url"),
                success: function (data) {
                    $.each(data.d, function () {
                        $(ctrl).append($('<option></option>').val(this.Value).html(this.Text));
                    });
                }
            });
        }
    });
    $('.AjaxSelect').live("change", function () {
            $("#" + this.id + "_hd").val($("#" + this.id + " option:selected").text() + "|" + $(this).val());
    });

}

function SumField() {
    $('.SumField').live("change", function () {
        var totalfield = $(".TotalField", this.parentNode.parentNode.parentNode);
        var sumfield = $(".SumField", this.parentNode.parentNode.parentNode)
        var sum = 0
        $(sumfield).each(function () {
            if (this.value != "")
            {
             sum += parseFloat(this.value) * parseFloat($("#" + this.id + "_hd").val());
            }           
        });
        $(totalfield).val(sum);

    });
}

function DirtyField() {
    $('.DirtyField').live("change", function () {
        var totalfield = $(".Dirty", this.parentNode.parentNode);
        
        $(totalfield).val("1");

    });
}

function NumericText() {
    $(".NumericText").live("keypress", function (e) {
        var key;
        if (e.charCode > 0) {
            key = e.charCode;
        }
        else {
            key = e.keyCode;
        }
        //alert(key);

        if ((key >= 48 && key <= 57) //0-9 
            || key == 8 //backspace
            || key == 9 //tab
            || (key >= 37 && key <= 40) //arrow keys
            || key == 45 //minus
            || key == 46 //delete
            ) 
        {
            return true;
        }
        else {
            return false;
        }
    });

    $(".NumericText").live("blur", function () {

            var value = $(this).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            var intRegex = /^[-]?\d+$/;
            if (!intRegex.test(value)) {
                $(this).val("0");
            }
            
        
    });
    }


function InitializeGridControls(sender, args) {

    $(".FlexGridField", $("#" + sender.get_id())).change(function () {

        setDirty($(this), sender.get_id());

    });

}

function setDirty(Field, GridID) {
    var hd = $("#" + GridID + "_dirty")
    if (hd.val().indexOf((Field.attr("rowid"))) < 0) {
        if (hd.val() == "" || hd.val() == null) {
            hd.val(Field.attr("rowid"));
        }
        else {
            hd.val(hd.val() + "," + Field.attr("rowid"));
        }
   }
       // alert(hd.val());
}




function formatDate(date) {
	return $.telerik.formatString('{0:yyyy-MM-dd}', date);
}

function PostAjax(url, data) {

	//data.replace("_", "");
	$.ajax({
		url: url,
		contentType: 'application/json; charset=utf-8',
		type: 'POST',
		dataType: 'json',
		error: function (xhr, status) {
			alert(status);
		},
		data: "{\"json\": " + JSON.stringify(data) + "}",
		success: function (result) {
			//alert("woot!");
		}
	});
}

function PostESAjax(url, data, dataFields) {

	for (var i=0; i < dataFields.length; i++) {
		ToJsonDate(data, dataFields[i]);
	}
	PostAjax(url, data);

	for (var i = 0; i < dataFields.length; i++ ) {
		ToGridDate(data, dataFields[i]);
	}
	for (var i = 0; i < data.length; i++) {		
		data[i]["esRowState"] = "Unchanged";
		data[i]["ModifiedColumns"] = [];
	}

}

function DirtyESItem(ctrl, data) {
	data[ctrl.id] = ctrl.value;
	data["esRowState"] = "Modified";
	data.ModifiedColumns.push(ctrl.id);
}

function ToJsonDate(data, field) {
	for (var i = 0; i < data.length; i++) {
		data[i][field] = '\/Date(' + data[i][field].getTime() + ')\/';
	}
}

function ToGridDate(data, field) {
	for (var i = 0; i < data.length; i++) {
		data[i]["GDate"] = new Date(+data[i]["GDate"].replace(/\/Date\((\d+)\)\//, '$1')); ;
	}
}







function get_Param(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 onMouseOver(ctrl) {
    ctrl.style.cursor = "pointer";
}

function onMouseOut(ctrl) {
    ctrl.style.cursor = "default";
}

function Increment(ctrlName, inc) {
    var ctrl = document.getElementById(ctrlName);
    ctrl.value = parseInt(ctrl.value) + parseInt(inc);

}



function onBlur(ctrl, dirtyctrl) {
    getDirtyCheck(ctrl, dirtyctrl);
    OnTextBlur(ctrl);
}

var FocusValue;
function OnTextFocus(ctrl) {
    ctrl.style.backgroundColor = "#CCCCCC";
}

function OnTextBlur(ctrl) {
    ctrl.style.backgroundColor = "";
}

var CleanValue;



function setDirtyCheck(ctrl) {
    CleanValue = ctrl.value;
}

function getDirtyCheck(ctrl, dirtyctrlid) {
    if (ctrl.value != CleanValue) {
        var temp = new Array();
        temp = ctrl.id.split("_");
        document.getElementById(dirtyctrlid).value = document.getElementById(dirtyctrlid).value + ',' + temp[temp.length - 1];
    }
}



function NumericOnly(event) {
    var key;
    if ("charCode" in event) {
        key = event.charCode;
    }
    else {
        key = event.keyCode;
    }


    if (key > 31 && (key < 48 || key > 57) && key != 45 && key != 109 && key != 189) {
        return false;
    }
    else {
        return true;
    }

}



function setNumericValue(ctrl) {
    //NumericValue = ctrl.value;
}

function checkNumericValue(ctrl) {
    if (ctrl.value != "") {
        if (parseInt(ctrl.value, 10) != ctrl.value - 0) {
            ctrl.value = CleanValue;
        }
    }
}


function MoveFocus(event, ctrl, vertCount) {
    var key;
    if ("keyCode" in event) {
        key = event.keyCode;
    }
    else {
        key = event.charCode;
    }

    if (key == 37) {
        doPrevious(ctrl, 1);
    }
    if (key == 38) {
        doPrevious(ctrl, vertCount);
    }

    if (key == 39) {
        doNext(ctrl, 1);
    }
    if (key == 40) {
        doNext(ctrl, vertCount);
    }

    if (key == 13) {
        doNext(ctrl, vertCount);
        return false;
    }

    if (key == 9) {
        //doNext(ctrl, 1);          
        //return false;
    }
}

function doNext(el, count) {
    //if (el.value.length < el.getAttribute('maxlength')) return;

    var f = el.form;
    var els = f.elements;
    var x, nextEl;
    for (var i = 0, len = els.length; i < len; i++) {
        x = els[i];
        if (el == x && (nextEl = els[i + count])) {
            if (nextEl.focus) {
                nextEl.focus();
                if (nextEl.options) {
                    nextEl.value = nextEl.options[nextEl.selectedIndex - 1].value;
                }
            }
        }
    }
}

function doPrevious(el, count) {
    //if (el.value.length < el.getAttribute('maxlength')) return;

    var f = el.form;
    var els = f.elements;
    var x, prevEl;
    for (var i = els.length, len = 0; i > len; i--) {
        x = els[i];
        if (el == x && (prevEl = els[i - count])) {
            if (prevEl.focus) {
                prevEl.focus();
                if (prevEl.options) {
                    prevEl.value = prevEl.options[prevEl.selectedIndex + 1].value;
                }

            }
        }
    }
}

function SelectText(event, ctrl) {
    var key;
    if ("keyCode" in event) {
        key = event.keyCode;
    }
    else {
        key = event.charCode;
    }

    if (key > 36 && key < 41) {
        ctrl.select();
    }
}


var RadGrid1;

function GetGridObject(sender, eventArgs) {
    RadGrid1 = sender;
}


function SetSelectedRow(gridid, row) {
    var masterTable = $find(gridid).get_masterTableView();
    masterTable.selectItem(masterTable.get_dataItems()[row].get_element());
}

function RowSelected(sender, args) {
    window.alert(args.get_owner().id);
}

function OnDateSelected(sender, args) {
    var temp = new Array();
    temp = sender.get_id().split("_");

    setDirty(sender.get_id(), temp[temp.length - 2] + "_dirty");
}

//Swaps values in a radcombobox; input is the client id of the radgrid
function ChangeOrder(cbo1, cbo2) {
    var combo1 = $find(cbo1);
    var combo2 = $find(cbo2);
    var value1 = combo1.get_value()

    var item1 = combo1.findItemByValue(combo2.get_value());
    if (!item1) {
        item1 = new Telerik.Web.UI.RadComboBoxItem()
        item1.set_text(combo2.get_text());
        item1.set_value(combo2.get_value());
        combo1.trackChanges()
        combo1.get_items().add(item1);
        combo1.commitChanges();
    }
    var item2 = combo2.findItemByValue(value1);
    if (!item2) {
        item2 = new Telerik.Web.UI.RadComboBoxItem()
        item2.set_text(combo1.get_text());
        item2.set_value(combo1.get_value());
        combo2.trackChanges()
        combo2.get_items().add(item2);
        combo2.commitChanges();
    }
    item1.select();
    item2.select();
}


//Clears items from a radcombobox to allow for lookup
function ClearItems(sender, eventArgs) {
    var text = sender.get_text();

    if (text.length > 1) {
        sender.set_text("");
    }
    else {
        sender.set_text(text);
    }

    sender.clearItems();
}

function ComboOnDemandBlur(sender, eventArgs) {

    if (sender.get_value() > 0) {

    }
    else {
        sender.set_text("");

    }
}

//Open radcombobox on focus
function ClientFocus(sender, eventArgs) {

    sender.set_closeDropDownOnBlur(true);
    sender.toggleDropDown();
}


function Navigate(sender, eventArgs) {

    var teams = get_Param("t");
    var mode = get_Param("mode");
    window.location = "default.aspx?mode=" + mode + "&t=" + teams;
}


var SelectedTab;

function ChangeTab(tab) {
    if (!SelectedTab) {
        SelectedTab = "GoogleTab"
    }

    document.getElementById(SelectedTab).className = "TabDiv";
    document.getElementById(tab).className = "TabDivSelected";
    document.getElementById(SelectedTab + "Form").style.display = "none";
    document.getElementById(tab + "Form").style.display = "block";
    document.getElementById(tab + "q").focus();
    document.getElementById(tab + "q").value = document.getElementById(SelectedTab + "q").value;
    SelectedTab = tab;

}

function Search()
{
    var SearchString;
    SearchString = "http://alpha.wissports.net/search.asp";
    SearchString = SearchString + "?client=pub-1864052687105654&forid=1&ie=ISO-8859-1&oe=ISO-8859-1&hl=en";
    SearchString = SearchString + '&q=' + document.getElementById('q').value + '&sitesearch=' + document.getElementById('sitesearch').value;
    SearchString = SearchString + "&cof=GALT%3A%23008000%3BGL%3A1%3BDIV%3A%23000000%3BVLC%3A663399%3BAH%3Acenter%3BBGC%3AFFFFFF%3BLBGC%3A000000%3BALC%3A000000%3BLC%3A000000%3BT%3A000000%3BGFNT%3Acc0000%3BGIMP%3Acc0000%3BLH%3A50%3BLW%3A100%3BL%3Ahttp%3A//www.wissports.net/images/200.jpg%3BS%3Ahttp%3A//alpha.wissports.net%3BFORID%3A1";
    window.location = SearchString;
}


function Search(Tab, SiteSearch) {
    var query = "cx=partner-pub-1864052687105654:4vyk7i-lul5";
    query = query + "&cof=FORID:10";
    query = query + "&ie=ISO-8859-1";
    query = query + "&SiteSearch=" + SiteSearch;
    query = query + "&q=" + document.getElementById(Tab + "q").value;
    if (Tab == '' && SiteSearch == '') {
        Tab = 'GoogleTab'
    }
    else {
        if (Tab == '' && SiteSearch != '') {
            Tab = 'WSNTab'
        }
    }
    query = query + "&tab=" + Tab;
    window.location = "http://www.wissports.net/search.asp?" + query;
}

function AdView(tpatID) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "HTTP://www.wissports.net/Services/SiteFunctions.asmx/AdView",
        data: "{TpatID: " + tpatID + "}",
        dataType: "json"
    });
}

function AdClickTpat(tpatID, url) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "HTTP://www.wissports.net/Services/SiteFunctions.asmx/AdClickTpat",
        data: "{TpatID: " + tpatID + "}",
        dataType: "json",
        success: function () { window.location = url; }
    });
}

function AdClick(tpaID, SchoolID, url) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "HTTP://www.wissports.net/Services/SiteFunctions.asmx/AdClick",
        data: "{TpaID: " + tpaID + ", SchoolID: " + SchoolID + "}",
        dataType: "json",
		success: function () { window.location= url;}
    });
}

function NavAdClick(NavItemAdID, url) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "HTTP://192.168.1.10/Services/SiteFunctions.asmx/NavAdClick",
        data: "{NavItemAdID: " + NavItemAdID + "}",
        dataType: "json",
        success: function () { window.location = url; }
    });
}


//Drop down menu code
	    //$(document).ready
		//	(function () {
		//
		//	    $(".MenuItem").hover(function () { //When trigger is clicked...  
		//	        var elem = $("#MenuDropDown[display='none']");
		//	        if ($("#MenuItem div:visible").size == 0) {
		//	            $(this).find(".MenuDropDown").slideDown('fast').show();
		//	        }
		//	        else {
		//	            $(".MenuDropDown").hide();
		//	            $(this).find(".MenuDropDown").show();
		//	        }

//			        $(".MenuDropDown", this).hover(function () {
//			        }, function () {
//			            $(".MenuDropDown").hide();
//			        });

//			    },
//				function () {
//				    $(".MenuDropDown").hide();
//				}
//				);
//			});

