﻿function FocusForWatermark(obj, explanation) {
    obj.style.color = '#222';
    obj.value = (obj.value == explanation) ? '' : obj.value; 
}
function BlurForWatermark(obj, explanation) {
    if (obj.value == '') {
        obj.value = explanation; obj.style.color = '#999';
     }
    else obj.value;
}

function OpenNewWindow(selectedInfo) {
    window.open("about:blank", "_formCas");
    $(document.NovartisCasReport).append("<input type='hidden' name='SelectedInfo' value='" + selectedInfo + "'>");
    $(document.NovartisCasReport).append("<input type='hidden' name='Detail' value='X'>");
    document.forms["NovartisCasReport"].target = "_formCas";
    document.forms["NovartisCasReport"].submit();
}

function SetIncotermLocation(obj) {
    if (obj.value == "EXW")
        document.getElementById("IncotermsLocation").value = "Fabrikada";
    else
        document.getElementById("IncotermsLocation").value = "";
}

var FaceboxTimer;
var clicked = false;  
function PrepareFaceboxToClose()
{
    FaceboxTimer = setTimeout("CloseFacebox()", 2000)
}

function CloseFacebox()
{
    if(FaceboxTimer)
        clearTimeout(FaceboxTimer);
    $.facebox.close();
}

function ChangeAllItemsValue(controlElement, refKey) {
    var form = document.forms[0];
    for (i = 0; i < form.elements.length; i++) {
        if (form.elements[i].id.toLowerCase().indexOf(refKey.toLowerCase()) >= 0)
            form.elements[i].value = controlElement.value;
        if (form.elements[i].id.toLowerCase().indexOf(("WinnerProduct_").toString().toLowerCase()) >= 0) {
            if (controlElement.value != 1)
                form.elements[i].value = "";
            else {
                var id = form.elements[i].id.substring();
                id = id.substring(id.indexOf(("WinnerProduct_").toString().toLowerCase()) + 15, id.length);
                form.elements[i].value = document.getElementById("tdItemText"+id).firstChild.nodeValue;
            }
        }
    }
}

function ChangeWinnerProductTextValue(controlElement) {
    var id = controlElement.id.substring();
    id = id.substring(id.indexOf(("Status_").toString().toLowerCase()) + 8, id.length);
    if (controlElement.value != 1) {
        document.getElementById("WinnerProduct_" + id).value = "";
        document.getElementById("Rival_" + id).value = "";

    }
    else
     {
         document.getElementById("WinnerProduct_" + id).value = document.getElementById("tdItemText" + id).firstChild.nodeValue;
         document.getElementById("Rival_" + id).value = document.getElementById("reval").value;
    }
}

function DeleteConfirmation() {
    var argv = DeleteConfirmation.arguments;

    if (argv[1] == "CreateTender") {
        $(document.CreateTender).append("<input type='hidden' name='DeletedItemNo' value='" + argv[2] + "'>");
        return true;
    }
    else {
        if (confirm(argv[0])) {
            $(document.EditTender).append("<input type='hidden' name='DeletedItemNo' value='" + argv[2] + "'>");
            return true;
        }
    }
    return false;
}

function OneTimeAccountAddressPopupValidation(OneTimeAccountform) {
    var name = OneTimeAccountform.elements["NAME1"].value;
    var city = OneTimeAccountform.elements["Region"].value;
    var country = OneTimeAccountform.elements["Country"].value;
    valid = true;
    if (name == null || name == "") {
        OneTimeAccountform.append("<input type='text' name='namenotvalid' value='namenotvalid'>");
        valid = false;
    }
    if (city == null || city == "") {
        OneTimeAccountform.append("<input type='text' name='citynotvalid' value='citynotvalid'>");
        valid = false;
    }
    if (country == null || country == "") {
        OneTimeAccountform.append("<input type='text' name='countrynotvalid' value='countrynotvalid'>");
        valid = false;
    }
    if (valid)
        OneTimeAccountform.submit();
}

function ShowMessage(Message, HideAutomaticly)
{
    if($("#SubmitPopup")) {$("#SubmitPopup").remove();}
    $("<div id='SubmitPopup' style='display:none; color:#000000;'></div>").insertAfter($("#ConstantPanel"));
    $.facebox({div:'#SubmitPopup'}, 'my-groovy-style');
    $.facebox.hideFooter();
    $("#SubmitPopup").html(Message + "<br><br><center><input id='SubmitPopup_OK' type='button' style='width:60px;' onclick='$.facebox.close();' class='Marker' value='OK'></center>");
    $('#SubmitPopup_OK').focus();
    if(HideAutomaticly)
        PrepareFaceboxToClose();
}

function ShowFaceBox()
{
		var title = 'Facebox title';
		var message = 'My message'; 		
        var box = new facebox({	
            title: title, 
            message: message 
            });
        box.show();
}

$(document).ready(function(){
		$("ul.sf-menu").supersubs({
			minWidth:    20,   
			maxWidth:    27,   
			extraWidth:  1     
		}).superfish();  
		
		$('.NavigatorMenu li').each(function(){
            this.onmouseover = function() { $(this).addClass("over"); $(this).children("ul").show(); };
            this.onmouseout = function() { $(this).removeClass("over"); $(this).children("ul").hide();};
        });
	});

function AutoCompleteResult(event, data, formatted)
{
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(document.OrderForm).append("<input type='hidden' name='AddToBasket?ID=" + SAPID + "' value='1'>")
    $(document.OrderForm).append("<input type='hidden' name='AddItem' value='1'>")
    document.OrderForm.submit();
}

function SubmitForCoskunozSalesReport(categoryName) {
    $(document.CoskunozSalesReport).append("<input type='hidden' name='SubmitedCategory' value='" + categoryName + "'>");
    document.CoskunozSalesReport.submit();
}

function AutoCompleteOnSearchResult(event, data, formatted) {
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);
    if (document.SearchPanel != null)
        document.SearchPanel.submit();
}

function FillMaterialGroup2() {
    document.getElementById("ProductGroup2").selectedIndex = 0;
    if (document.SearchPanel != null)
        document.SearchPanel.submit();
    else if (document.ProductSearch != null)
        document.ProductSearch.submit();
}

function AutoCompleteBasicResult(event, data, formatted) {
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);
}

function AutoCompleteInventoryResult(event, data, formatted) {
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);
    var txtText = document.getElementById('txtDesc');
    txtText.value = " - " + Name;

}


function SetOrderQuantityValue(baseControl, destinationId, quantityId) {
    if (!IsNumeric(baseControl.value)) {baseControl.value = "";  document.getElementById(destinationId).value = 0; }
    else {
        document.getElementById(destinationId).value = parseInt(baseControl.value) * parseInt(document.getElementById(quantityId).value);
    }
}

function SetSecondRivalPriceValue(baseControl, destinationId, destinationValue) {
if(!baseControl.checked)
    document.getElementById(destinationId).value = destinationValue;
}

function SetControlValue(baseControl, destinationControlId, controlValue, valueType) {
    if (baseControl.type == 'checkbox' && baseControl.checked == true)
        if (valueType == 'number')
            document.getElementById(destinationControlId).value = parseInt(controlValue);
}

function AutoCompleteNameInTdMaterialResult(event, data, formatted) {
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);
    var txtText = document.getElementById('txtItemText');
    txtText.value = " - " + Name;
}

function insertOptionBefore() {
    var elSel = document.getElementById('selectX');
    if (elSel.selectedIndex >= 0) {
        var elOptNew = document.createElement('option');
        elOptNew.text = document.getElementById('Material').value;
        elOptNew.value = document.getElementById('Material').value;
        var elOptOld = elSel.options[elSel.selectedIndex];
        try {
            elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
        }
        catch (ex) {
            elSel.add(elOptNew, elSel.selectedIndex); // IE only
        }
    }
}

function removeOptionSelected() {
    var elSel = document.getElementById('selectX');
    var i;
    for (i = elSel.length - 1; i >= 0; i--) {
        if (elSel.options[i].selected) {
            elSel.remove(i);
        }
    }
}



function AutoCompleteNameInTdInstitutionResult(event, data, formatted) {
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);
    var txtText = document.getElementById('txtInstitutionText');
    txtText.value = " - " + Name;
}

function AutoCompleteCountryResult(event, data, formatted)
{
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);
}

function FilteredAddressResult(data, addressType, step) {
    $(document.OrderForm).append("<input type='hidden' name='FilteredAddressType' value='" + addressType + "'>");
    $(document.OrderForm).append("<input type='hidden' name='FilteredAddressResult' value='" + data + "'>");
    $(document.OrderForm).append("<input type='hidden' name='AddressPopupFired' value='" + step + "'>");
    document.OrderForm.submit();
}

function DeleteOneTimeAddress(val) {
    $(document.OrderForm).append("<input type='hidden' name='DeleteAddress' value='" + val + "'>");
    $(document.OrderForm).append("<input type='hidden' name='AddressPopupFired' value='2'>");
    document.OrderForm.submit();
}

function AutoCompleteAddressResult(event, data, formatted) {
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);
    $(document.OrderForm).append("<input type='hidden' name='AddressResult' value='1'>");
    document.OrderForm.submit();
}

function AutoCompleteBillingAddressResult(event, data, formatted) {
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);
    $(document.OrderForm).append("<input type='hidden' name='BillingAddressResult' value='1'>");
    document.OrderForm.submit();
}

function AutoCompleteDeliveryAddressResult(event, data, formatted) {
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);
    $(document.OrderForm).append("<input type='hidden' name='DeliveryAddressResult' value='1'>");
    document.OrderForm.submit();
}

function AutoCompleteAddressCountryResult(event, data, formatted) {
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);
}

function AutoCompleteAddressRegionResult(event, data, formatted) {
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);   
}

function AutoCompleteCustomerResult(event, data, formatted) {
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);
    document.OrderForm.submit();
}

function AutoCompleteCustomerPopupResult(event, data, formatted) {
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(SAPID);
}

function AutoCompleteInstitutionPopupResult(event, data, formatted) {
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    $(this).val(ID);
}

function CheckDate(Box) {
    if (Box.value.indexOf('.') == -1 && Box.value.indexOf('/') == -1) {
        if (Box.value != "") {
            var Current = new Date();
            var Value = Box.value;
            if (Box.value.length == 4) {
                Value = "0" + Box.value.substr(0, 1) + "." + "0" + Box.value.substr(1, 1) + "." + (Current.getFullYear() + "").substr(0, 2) + Box.value.substr(2, 2);
            }
            else if (Box.value.length == 6)
                Value = Box.value.substr(0, 2) + "." + Box.value.substr(2, 2) + "." + (Current.getFullYear() + "").substr(0, 2) + Box.value.substr(4, 2);
            else if (Box.value.length == 8)
                Value = Box.value.substr(0, 2) + "." + Box.value.substr(2, 2) + "." + Box.value.substr(4, 4);
            Box.value = Value;
        }
    } else {
        if (Box.value.indexOf('/') > 0) {
            var d = "";
            var m = "";
            var y = "";
            var j = 0;
            for (i = 0; i < Box.value.length; i++)
                if (Box.value[i] != "/") {
                    if (j == 0)
                        d += Box.value[i];
                    else if (j == 1)
                        m += Box.value[i];
                    else if (j == 2)
                        y += Box.value[i];
                }
                else j++;
            if (d.length < 2)
                d = "0" + d;
            if (m.length < 2)
                m = "0" + m;
            Box.value = d + "." + m + "." + y;
        }

    }
}

function Toggle(param) {
    if (param == 1) {
        if (document.getElementById("HideableRow1").style.display == 'none') {
            document.getElementById("HideableRow1").style.display = '';
        } else {
            document.getElementById("HideableRow1").style.display = 'none';
        }
    }
    else {
        if (document.getElementById("HideableRow2").style.display == 'none') {
            document.getElementById("HideableRow2").style.display = '';
        } else {
            document.getElementById("HideableRow2").style.display = 'none';
        }    
    }
}

function ToggleTenderPrice(listControl) {
    var selIndex = listControl.selectedIndex;
    var name = listControl.name.substring(7);
    if (selIndex == 1) {
        document.getElementById("headerFirstOrderDateTd").style.display = '';
        document.getElementById("headerFirstOrderQuantityTd").style.display = '';
        document.getElementById("valueFirstOrderDateTd" + name).style.display = '';
        document.getElementById("valueFirstOrderQuantityTd" + name).style.display = '';

        document.getElementById("headerRivalTd").style.display = 'none';
        document.getElementById("headerPriceTd").style.display = 'none';
        document.getElementById("valueRivalTd" + name).style.display = 'none';
        document.getElementById("valuePriceTd" + name).style.display = 'none';
        document.getElementById("Rival_" + name).value = 0;
        document.getElementById("Price_" + name).value = "";    
    }
    else if (selIndex == 2) {
        document.getElementById("headerRivalTd").style.display = '';
        document.getElementById("headerPriceTd").style.display = '';
        document.getElementById("valueRivalTd" + name).style.display = '';
        document.getElementById("valuePriceTd" + name).style.display = '';

        document.getElementById("headerFirstOrderDateTd").style.display = 'none';
        document.getElementById("headerFirstOrderQuantityTd").style.display = 'none';
        document.getElementById("valueFirstOrderDateTd" + name).style.display = 'none';
        document.getElementById("valueFirstOrderQuantityTd" + name).style.display = 'none';
        document.getElementById("FirstOrderDate_" + name).value = "";
        document.getElementById("FirstOrderQuantity_" + name).value = "";   
    }
    else {
        document.getElementById("headerFirstOrderDateTd").style.display = 'none';
        document.getElementById("headerFirstOrderQuantityTd").style.display = 'none';
        document.getElementById("valueFirstOrderDateTd" + name).style.display = 'none';
        document.getElementById("valueFirstOrderQuantityTd" + name).style.display = 'none';
        document.getElementById("FirstOrderDate_" + name).value = "";
        document.getElementById("FirstOrderQuantity_" + name).value = "";

        document.getElementById("headerRivalTd").style.display = 'none';
        document.getElementById("headerPriceTd").style.display = 'none';
        document.getElementById("valueRivalTd" + name).style.display = 'none';
        document.getElementById("valuePriceTd" + name).style.display = 'none';
        document.getElementById("Rival_" + name).value = 0;
        document.getElementById("Price_" + name).value = "";                 
    }
}

function ShowIndividualTender(listControl) {
    var individualID = listControl.options(listControl.selectedIndex).value;
    newUrl = "DisplayTender.aspx?&TenderID=" + individualID;
    window.open(newUrl,'_blank');
}

//function CheckDate(Box)
//{
//    if(Box.value.indexOf('.') == -1 && Box.value.indexOf('/') == -1)
//    {
//        $(Box).DatePicker(        { format:Box.options.format,date: Box.options.date, current: Box.options.current, starts: Box.options.starts, onBeforeShow: Box.options.onBeforeShow, onChange: Box.options.onChange }         ); 
//        $(Box).SetDefaults();
//        $(Box).val($(Box).DatePickerFormatDate(Box.options.current, Box.options.format));
//    } 
//}

function SaveOrder(e) 
{
    if (document.getElementById("SaveOrder").value == "0") {

        document.getElementById("SaveOrder").value = "1"; 
        document.OrderForm.submit();
    }
    else {
        alert("İşleminiz yapılıyor. Lütfen bekleyiniz.");
    }
}

function FormatItem(row)
{
    var formatted = "" + row;
    var SAPID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(SAPID + " ", "");
    var ID = formatted.substring(0, formatted.indexOf(" "));
    formatted = formatted.replace(ID + " ", "");
    var Name = formatted;
    return SAPID + " " + Name;
}
function UpdateBindings() {
    $(".AutoComplete").each(
        function() {
            $(this).unbind("autocomplete");
            $(this).autocomplete(this.title, { max: 20, width: 500, multiple: this.title.indexOf("Multiple=true") > -1, matchContains: true }).result(AutoCompleteResult);
        });
}


$(document).ready(function () {


    $(function () { $(".InventoryAutoComplete").autocomplete('/Search.aspx?Type=InventoryMaterial', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteInventoryResult); });

    $(function () { $('.Gallery a').lightBox({ fixedNavigation: true }); });

    $(function () { $('.Numeric').numeric(","); })

    $(function () { $(".sortable").tablesorter(); });

    $(function () { $(".MaterialAutoComplete").autocomplete('/Sales/Catalog/Catalog.aspx?Ajax=1&Type=1', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteResult); });

    $(function () { $(".MaterialAutoCompleteOnSearch").autocomplete('/Sales/Catalog/Catalog.aspx?Ajax=1&Type=1', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteOnSearchResult); });

    $(function () { $(".CustomerAutoComplete").autocomplete('/Sales/Catalog/Customer.aspx?Ajax=1&Type=1', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteCustomerResult); });

    $(function () { $(".CustomerAutoCompletePopup").autocomplete('/Sales/Catalog/Customer.aspx?Ajax=1&Type=1', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteCustomerPopupResult); });

    $(function () { $(".InstitutionAutoCompletePopup").autocomplete('/Sales/Catalog/Institution.aspx?Ajax=1&Type=1', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteInstitutionPopupResult); });

    $(function () { $(".CountyAutoComplete").autocomplete('/Sales/Catalog/Catalog.aspx?Ajax=1&ListCountry=1', { width: 250, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteCountryResult); });

    $(function () { $(".MaterialAutoCompleteBasic").autocomplete('/Sales/Catalog/Catalog.aspx?Ajax=1&Type=1', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteBasicResult); });

    $(function () { $(".MaterialAutoCompleteNameInTd").autocomplete('/Sales/Catalog/Catalog.aspx?Ajax=1&Type=1&Tender=1', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteNameInTdMaterialResult); });

    $(function () { $(".InstitutionAutoCompleteNameInTd").autocomplete('/Sales/Catalog/Institution.aspx?Ajax=1&Type=1&Region=' + $('select#Region').val(), { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteNameInTdInstitutionResult); });

    $(function () { $(".AddressAutoComplete").autocomplete('/Search.aspx?Type=Address', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteAddressResult); });

    $(function () { $(".BillingAddressAutoComplete").autocomplete('/Search.aspx?Type=Address', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteBillingAddressResult); });

    $(function () { $(".DeliveryAddressAutoComplete").autocomplete('/Search.aspx?Type=Address', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteDeliveryAddressResult); });

    $(function () { $(".AddressCountryAutoComplete").autocomplete('/Search.aspx?Type=Country', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteAddressCountryResult); });

    $(function () { $(".AddressRegionAutoComplete").autocomplete('/Search.aspx?Type=Region', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteAddressRegionResult); });

    $(function () { $(".AddressCountryAutoComplete").autocomplete('/Search.aspx?Type=Country', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteAddressCountryResult); });

    $(function () { $(".AddressRegionAutoComplete").autocomplete('/Search.aspx?Type=Region', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteAddressRegionResult); });

    $(function () {

        $('a[rel*=facebox]').each(
            function () {
                $(this).unbind("click");
                $(this).click(function () { $.facebox({ ajax: this.href }, 'my-groovy-style'); return false; });
            }
        );

        $('#Annoucements marquee').marquee('pointer').mouseover(function () {
            $(this).trigger('stop');
        }).mouseout(function () {
            $(this).trigger('start');
        }).mousemove(function (event) {
            if ($(this).data('drag') == true) {
                this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
            }
        }).mousedown(function (event) {
            $(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
        }).mouseup(function () {
            $(this).data('drag', false);
        });
    });

    $(function () {
        $('#Warnings marquee').marquee('pointer').mouseover(function () {
            $(this).trigger('stop');
        }).mouseout(function () {
            $(this).trigger('start');
        }).mousemove(function (event) {
            if ($(this).data('drag') == true) {
                this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
            }
        }).mousedown(function (event) {
            $(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
        }).mouseup(function () {
            $(this).data('drag', false);
        });
    });

    sitemapstyler();



});



function ShowAverageDueDate()
{
    var Val = "";
    $('.cbItems').each(
                function(){
                if(this.checked)
                {
                    if(Val != "")
                    Val = Val + ",";
                Val = Val + $(this).val();
                }
            });
    $.facebox({ajax:"/Accounting/AverageDueDate.aspx?cbItems=" + Val}, 'my-groovy-style');
}


function ShowPopUp(ID)
{
    $(document).ready(function(){	
        $.facebox({div:'#' + ID}, 'my-groovy-style');
        });
}

function ShowAddressPopUp(ID) {
    if (ID == null)
        ID = '0';
    $.facebox({ ajax: "/PopUp/OneTimeAddress.aspx?ToPage=/Sales/Sales/NewOrder.aspx&SelectedAddressId=" + ID }, 'my-groovy-style');
}

function DropRegionList()
 {
    $.autocomplete('/Search.aspx?Type=Region', { width: 400, multiple: false, matchContains: true, formatItem: FormatItem }).result(AutoCompleteAddressRegionResult);

}

function GoHomePage() {
    window.location = "/Default.aspx";
}

function FocusNextControlAfterSomeChar(firstControlId, secondControlId, stringCount) {
    var val = document.getElementById(firstControlId).value;
    if (val.length >= stringCount)
        (document.getElementById(secondControlId)).focus();
}

function ShowHideFrame() {
    var fr = document.getElementById("coskunozCategoryViewer");
    var hidden = document.getElementById("ShowHideStatus");
    var image = document.getElementById("CategoryShowHideButtonImage");
    if (fr.style.display == "none") {
        fr.style.display = "block";
        hidden.value = "block";
        image.src = "/Images/CategoryShowHideButton/hide.png";
    }
    else {
        fr.style.display = "none";
        hidden.value = "none";
        image.src = "/Images/CategoryShowHideButton/show.png";
    }
}

function LoadPanel(Panel, Href)//Bir paneli blok halinde yukler, loading animasyonunu bu panel icerisinde gosterir.
{
    var P = $("#" + Panel);
    if(Href.indexOf('?') == -1)
        Href = Href + "?";
    $.ajax({
      cache: false,
      type: "POST",
      url: Href + "&rnd=" + Math.random(),
      data: "",
      success: function(response) {
        P.html(response);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown){
        
      }
     });
    return false;
}

function CalculateTotal(TextBox)
{
    var SAPID = TextBox.name.replace("StockQuantity", "");
    var Q = TextBox.value;
    var Price = document.getElementById('Price_' + SAPID.replace("2?","").replace("?","")).value.replace(".", "").replace(",", ".");
    if(!IsNumeric(Q))
        Q = 0;
     document.getElementById('Total' + SAPID).innerHTML = Round(Q * Price, 2);
}

function Round(number,decimals) {
	var newString;// The new rounded number
	decimals = Number(decimals);
	if (decimals < 1) {
		newString = (Math.round(number)).toString();
	} else {
		var numString = number.toString();
		if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
			numString += ".";// give it one at the end
		}
		var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
		var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
		var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
		if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
			if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
				while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
					if (d1 != ".") {
						cutoff -= 1;
						d1 = Number(numString.substring(cutoff,cutoff+1));
					} else {
						cutoff -= 1;
					}
				}
			}
			d1 += 1;
		} 
		if (d1 == 10) {
			numString = numString.substring(0, numString.lastIndexOf("."));
			var roundedNum = Number(numString) + 1;
			newString = roundedNum.toString() + '.';
		} else {
			newString = numString.substring(0,cutoff) + d1.toString();
		}
	}
	if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
		newString += ".";
	}
	var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
	for(var i=0;i<decimals-decs;i++) newString += "0";
	//var newNumber = Number(newString);// make it a number if you like
	return newString; // Output the result to the form field (change for your purposes)
}


function IsNumeric(sText)
{
    if(sText != undefined && sText != null && sText != "")
    {
        var ValidChars = "0123456789.,";
        var IsNumber=true;
        var Char;
       for (i = 0; i < sText.length && IsNumber == true; i++) 
          { 
          Char = sText.charAt(i); 
          if (ValidChars.indexOf(Char) == -1) 
             {
             IsNumber = false;
             }
          }
       return IsNumber;
    }
    return false;
}

function check_tabletotal(sumquantity,message) {
   var total=0;
   
   var otable = document.getElementById("MaterialTable");

   for (var i = 0; i < (otable.rows.length - 2); i++) {
      
       total= parseInt(total) + parseInt(document.getElementById("MaterialSAPID_" + i).value);   
   
   }

   if (total !=  parseInt(sumquantity)) {
       alert(message);
       return false;
   }

   else return true;

}

function check_tablelements(oMessage) {

    var elems = OrderForm.elements;
    var elemsLength = OrderForm.elements.length;

    var totalzero = 0;

    for (var i = 0; i < elemsLength; i++) {
     var field = elems[i];
     if (field.type && field.type == "text") {
         fieldName = field.name;
         fieldValue = field.value;

         if (fieldName.indexOf("Quantity",0) != -1 && fieldValue != '' && parseInt(fieldValue)==0 )
             totalzero++; 
      }

    }

    if (parseInt(totalzero) > 0) {
        alert(oMessage); 
        return false;
    }
    else return true;

}

function CheckBrowser() {
    if (clicked == false) {
        //Browser closed   
    } else {
        //redirected
        clicked = false;
    }
}
function bodyUnload() {

    var str = "0";
    try {
        str = document.getElementById('ExportToExcel').value;
    } catch (e) {
    str = "0";
    }

    try {
    str = document.getElementById('ConfirmBasket').value;  
    } catch (e) {
    str = "0";
    } 
    

    if (str =="1") {
        clicked = true;
    }
    if (clicked == false)//browser is closed  
    {
        var request = GetRequest();
        
        request.open("GET", "../Community/Logout.aspx", false);
        request.send();

    }
}
//function bodyUnload() {
//    var url = top.location.href.toString();
//    if (top.location == self.location)//browser is closed  
//    {
//        if (url.indexOf("Login") == -1) {
//            var request = GetRequest();
//            request.open("GET", "../Community/Logout.aspx?NoFrame=1", false);
//            request.send();
//        }


//    }
//}
function GetRequest() {
    var xmlHttp = null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        //Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

function ToUpperCase(o){o.value=o.value.toUpperCase();}

function CheckNumeric(e) {

  if( window.event ){
     if (e.keyCode < 48 || e.keyCode > 57) {
         event.returnValue = false;
         return false;
     }

 } 
 else {
    if (e.which < 48 || e.which > 57) {
        return false;
    }
  }
}

function runScript(e, MaterialId) {
    if (e.keyCode == 13) {
      
        document.OrderForm.submit(); 
        return false;
    } 
} 


//function OnFocusQuantity (MaterialId) {
//    var code = null;
//    var testTextBox = $("#" + MaterialId);

//    testTextBox.keypress(function () {
//        alert("Handler for .keypress() called.");
//    });

////    testTextBox.keypress(function (e) {
////        code = (e.keyCode ? e.keyCode : e.which);
////        if (code == 13) document.OrderForm.submit();
////        e.preventDefault();
////    });
//}  


function PaymentValidation(withoutorder) {

    if ($("#BankList").val() == '' || $("#BankList").val() == '0') {
        $.facebox({ ajax: "/PopUp/JSMessage.aspx?JSMessage=SelectABank" }, 'my-groovy-style');
        return false;
    }

    if ($("#PartialPayment").val() == '' || $("#PartialPayment").val() == '0') {
        $.facebox({ ajax: "/PopUp/JSMessage.aspx?JSMessage=PartialPaymentValueRequired" }, 'my-groovy-style');
        return false;
    }


    if ($("#NameOnCard").val() == '') {
    
        $.facebox({ ajax: "/PopUp/JSMessage.aspx?JSMessage=NameOnCreditCardRequired" }, 'my-groovy-style');
        return false;
    }

    if ($("#CreditCardType").val() == '' || $("#CreditCardType").val() == '0') {
        $.facebox({ ajax: "/PopUp/JSMessage.aspx?JSMessage=CreditCardTypeRequired" }, 'my-groovy-style');
        return false;
    }

    if (($("#CreditCardNum00").val() == '') || $("#CreditCardNum00").val().length < 4) {
        $.facebox({ ajax: "/PopUp/JSMessage.aspx?JSMessage=ValidCreditCardNumberRequired" }, 'my-groovy-style');
        return false;
    }
    if (($("#CreditCardNum01").val() == '') || $("#CreditCardNum01").val().length < 4) {
        $.facebox({ ajax: "/PopUp/JSMessage.aspx?JSMessage=ValidCreditCardNumberRequired" }, 'my-groovy-style');
        return false;
    }

    if (($("#CreditCardNum02").val() == '') || $("#CreditCardNum02").val().length < 4) {
        $.facebox({ ajax: "/PopUp/JSMessage.aspx?JSMessage=ValidCreditCardNumberRequired" }, 'my-groovy-style');
        return false;
    }

    if (($("#CreditCardNum03").val() == '') || $("#CreditCardNum03").val().length < 3) {
        $.facebox({ ajax: "/PopUp/JSMessage.aspx?JSMessage=ValidCreditCardNumberRequired" }, 'my-groovy-style');
        return false;
    }
    
   

    if ($("#CreditCardCCV").val() == '') {
        $.facebox({ ajax: "/PopUp/JSMessage.aspx?JSMessage=CreditCardCCVRequired" }, 'my-groovy-style');
        return false;
    }

    if (withoutorder == "1") {

        if ($("#PaymentAmount").val() == '') {
            $.facebox({ ajax: "/PopUp/JSMessage.aspx?JSMessage=EnterPaymentAmount" }, 'my-groovy-style');
            return false;
        }
    }
    
    return true;
}

function PaymentOptionVisible() {

    if($("#PaymentType").val() !="A") 
    document.getElementById("Credits").disabled = true;  
} 

function testPassword(password) {

    var intScore = 1;
    var strVerdict = "weak";

    if (password.length >= 4) 
    {
        // PASSWORD LENGTH
        if (password.length >= 6) 
        {
            intScore = (intScore + 1);
        }
        if (password.length >= 12)// length between 8 and 15
        {
            intScore = (intScore + 1);
        }
        if (password.match(/\d+/))                                 // [verified] at least one number
        {
            intScore = (intScore + 1);
        }
        if (password.match(/[a-z]/))                              // [verified] at least one lower case letter
        {
            intScore = (intScore + 1);
        }
        if (password.match(/[A-Z]/)) 
        {
            intScore = (intScore + 1);
        }
        if (password.match(/.[!,@,#,$,%,^,&,*,?,_,~]/))            // [verified] at least one special character
        {
            intScore = (intScore + 1);
        }
        if ((password - 0) == password && password.length > 0) 
        {
            intScore = (intScore - 1);
        }
    }
    else 
    {
        if (password.Length < 1) 
        {
            intScore = 0;
        }
        else if (password.Length < 4) 
        {
            intScore = 1;
        }
    }
    if (intScore == 0) 
    {
        strVerdict = "useless"
    }
    else if (intScore == 1) 
    {
        strVerdict = "very weak";
    }
    else if (intScore == 2) 
    {
        strVerdict = "weak";
    }
    else if (intScore == 3) 
    {
        strVerdict = "medium";
    }
    else if (intScore == 4) 
    {
        strVerdict = "fair";
    }
    else if (intScore == 5)
     {
        strVerdict = "good";
    }
    else if (intScore == 6) 
    {
        strVerdict = "strong";
    }
    else if (intScore == 7) 
    {
        strVerdict = "very strong";
    }
   // alert(intScore);
    // alert(strVerdict);
   
    //document.forms.passwordForm.score.value = (intScore)
    document.forms.UserForm.passwordStrength.value = (strVerdict)

}

function toggle(chkbox, field) {
    if (field.length == null)
        field.checked = chkbox.checked;
    else
        for (i = 0; i < field.length; i++)
            field[i].checked = chkbox.checked;
}









