﻿$(document).ready(function(){   
    AddFavIcon();
    var isDefault = false;
    
    if(document.URL.toLowerCase().indexOf('default.aspx') != -1 && (SiteId == '1' || SiteId == '4')) {
        isDefault = true;
    }
    
    var sourceCodeImage = $('.sourceCodeImage').attr('src');
    
    if(sourceCodeImage == '/graphics/1pix.gif') {
        $('.sourceCodeLink').hide();
    }
            
    //if($.browser.mozilla) $("form").attr("autocomplete", "off"); 
    
    /*
    if(ShowEmailSignUpPopUp) {// && isDefault
        alert('show');
        var t = setTimeout(ShowEmailSignUp, EmailSignUpPopUpDelay);
    }*/
         
    if(HeaderBackgroundElement != '') {
        $(HeaderBackgroundElement).css('background-image', 'url('+HeaderBackgroundImage+')');
        
        if(HeaderURL != '') {
            $('.logoURL', HeaderBackgroundElement).attr('href',HeaderURL);
        }
        
        if(HeaderTitle != '') {
            $('.logoURL', HeaderBackgroundElement).attr('title',HeaderTitle);
        }            
        
        if(HeaderAlt != '') {
            $('.logoURL', HeaderBackgroundElement).attr('alt',HeaderAlt);
        }            
    }
    
    if (IsUserAuthenticated.toLowerCase() == 'false' && (SiteId == 2 || SiteId == 3)) {
        $('#CartNav').hide();
        $('#tabs').hide();
    }
    
    //05-07-10 10:24:26 avc >>dont use if js is in ext file
    //08-27-09 avc >> set default apptheme path...
    /*
    try {
        $.fn.quickview.defaults.AppTheme = AppTheme;
    }
    catch (err) {}*/
    
    //20100806 13:35:48 avc >>hide hover cart
    //08-20-09 avc >> setup cart hover
    //$("#CartTopBox").hoverIntent( BindCartHover, DoNothing );
    var lastMenuLIOver = '';
    //20101005 11:05:57 avc >>bind mouseover for top level menu items
    if(AjaxNavigation == 'True') {
        $('li', 'ul.sf-menu').each(function() {
            var pk_dcid = $(this).attr('id');
            $.get('/WebServices/DeptCategorize.asmx/BuildDepartmentString',{ParentId:pk_dcid,MenuIsAllCaps:"True"}, function(data) {
                $(data).find('string').each(function() {
                    $('li#'+pk_dcid).append($(this).text());
                    //$('li.toplevel').children('a').children('.sf-sub-indicator').hide();
                });
            });        
            /*
            $(this).bind('mouseover', function(e){
                var pk_dcid = $(this).attr('id');
                var getSubs = $(this).attr('getSubs');
                
                if(getSubs == null || getSubs == '') {
                    $(this).unbind('mouseover');
                    $(this).attr('getSubs', 'false');
                    $.get('/WebServices/DeptCategorize.asmx/BuildDepartmentString',{ParentId:pk_dcid,MenuIsAllCaps:"True"}, function(data) {
                        $(data).find('string').each(function() {
                            //alert($(this).text());
                            //alert('menu data received');
                            $('li#'+pk_dcid).append($(this).text());
                            $("ul.sf-menu").superfish({showID:pk_dcid});
                            //$('ul.sf-menu').children('li').children('a').children('.sf-sub-indicator').hide();
                            $('li.toplevel').children('a').children('.sf-sub-indicator').hide();
                            lastMenuLIOver = 'li#'+pk_dcid;
                            var t = setTimeout(showLI, 2000);
                        });
                    });                    
                }
            });            
            */
        });
        $("ul.sf-menu").superfish();
    }
    
    function showLI() {
        //alert('showLI: '+lastMenuLIOver);
        console.log(lastMenuLIOver);
        $(lastMenuLIOver).trigger('click');
    }
    
    if(HideNavigation == 'True') {
        $('#tabs').hide();
    }
    
    if(HideSearchBar == 'True') {
        $('#container').css('clear','both');
    }
});

function ShowEmailSignUp() {
    //alert('ShowEmailSignUp');
    showWindow('#EmailSignUp', 'Email Sign Up', true, true);
}

function AddFavIcon() {
	try {
		var favlink = document.createElement('link');
		favlink.type = 'image/x-icon';
		favlink.rel = 'shortcut icon';
		
		if(document.domain == 'budk.com' || document.domain == 'budk.comloginc.net') {
			favlink.href = 'http://budk.com/graphics/budK_FAVicon.ico';
		}
		
		if(document.domain == 'budkws.comloginc.net' || document.domain == 'budkwholesale.com') {
			favlink.href = 'http://budk.com/app_themes/budkws.com/graphics/budK_FAVicon.ico';
		}            

		if(document.domain == 'kennesawcutlery.com' || document.domain == 'budkken.comloginc.net') {
			favlink.href = 'http://budk.com/graphics/KC_FAVicon.ico';
		}            
		
		if(document.domain == 'matthewscutlery.com' || document.domain == 'budkmat.comloginc.net') {
			favlink.href = 'http://budk.com/app_themes/budkmat.com/graphics/MC_FAVicon.ico';
		}                        
		
		//$('head').append(favlink);                    
		document.getElementsByTagName('head')[0].appendChild(favlink);	
	}
	catch (err) {}
}

function DoNothing() { }

function BindCartHover() {
    //08-20-09 avc >> bind our event
    //$("#CartTopBox").bind("mouseover", function(e){
        if(CartItemCount > 0) {
            var pos = $("#CartTopBox").offset();
            //unbind so it doesnt fire after first time
            //$("#CartTopBox").unbind("mouseover");
            //setup the style
            var style = 'display:none;border:1px solid #555;background-color:#FFF;z-index:99999;cursor:pointer;position:absolute;top:'+(pos.top+40)+'px;left:'+(pos.left-86)+'px;';
            //append the new div to dom
            $('body').append('<div id="CartHover" style="'+style+'"></div>');
            AjaxBlock('#CartTopBox');
            //load the carthover page via ajax when complete call showcarthover
            $("#CartHover").load("/CartHover.aspx?rnd=" + Math.random(), null, ShowCartHover);      
            //setup event to hide carthover when user mouses out          
            $("#CartHover").bind("mouseleave", function(e){
                HideCartHover();
            });
        }
    //});
    
    ShowCartHover();    
}

function ShowCartHover() {
    setTimeout('$("#CartTopBox").unblock()', 800);
    $("#CartHover").slideDown('slow');
}

function HideCartHover() {
    //slid div up and when complete remove it from dom and rebind original event
    $("#CartHover").slideUp('slow', function() {
        $("#CartHover").remove();    
        //BindCartHover();                
    });
}    

function AjaxBlock(obj) {
    $(obj).block({ 
        message: '<img src="/graphics/loading.gif" />', css: {border:'none'} 
    });    
}

function Block(obj) {
    $(obj).block({ 
        message: '', css: {border:'none'} 
    });    
}    

function UnBlock(obj, delay) {
    if(delay == null) delay = 800;
    setTimeout('$("'+obj+'").unblock()', delay);
}

function submitSearch(val) 
{    
    //LIVE SEARCH LINK
    var newLink = '';
    
    if(val == '') {
        if(document.domain == 'budk.com' || document.domain == 'budk.comloginc.net') {
            newLink = 'http://knives.budk.com/search?asug=&w=' + $('#cli_search_budk').val();// document.getElementById("cli_search_budk").value;        
            //newLink = '/results.aspx?k=' + replaceSpecialCharacter($("#cli_search_budk").val());
        } else if(document.domain == 'kennesawcutlery.com' || document.domain == 'budkken.comloginc.net') {
            newLink = 'http://knives.kennesawcutlery.com/search?asug=&w=' + $('#cli_search_ken').val();
            //newLink = '/results.aspx?k=' + replaceSpecialCharacter($("#cli_search_ken").val());
        } else if(document.domain == 'budkwholesale.com' || document.domain == 'budkws.comloginc.net') {
            newLink = '/results.aspx?k=' + replaceSpecialCharacter($("#cli_search_ws").val());
        } else if(document.domain == 'matthewscutlery.com' || document.domain == 'budkmat.comloginc.net') {
            newLink = '/results.aspx?k=' + replaceSpecialCharacter($("#cli_search_mat").val());
        } else if(document.domain == 'chkadels.com' || document.domain == 'budkchk.comloginc.net') {
            newLink = '/results.aspx?k=' + replaceSpecialCharacter($("#cli_search_chk").val());
        } 
    } else {
        newLink = '/results.aspx?k=' + replaceSpecialCharacter(val);
    }
    
    location.href = newLink;
}  

function replaceSpecialCharacter(val) 
{
    val = val.replace('&','%26');
    val = val.replace('\'','%27');
    val = val.replace('<','%3C');
    val = val.replace('>','%3E');
    val = val.replace('"','%22');
    val = val.replace('\\','%5C');
    val = val.replace(';','%3B');
    val = val.replace('/','%2F');
    val = val.replace('?','%3F');
    val = val.replace('=','%3D');
    val = val.replace('#','%23');
    val = val.replace(',','%2C');
    val = val.replace('+','%2B');
    val = val.replace('$','%24');
    val = val.replace(':','%3A');
    
    return val;
}

function checkEnter(e)
{ 
    try 
    {   //try the easy check - if they pressed enter, then submit the search and return false.
        if (13 == (e.charCode || e.keyCode))
        {
            submitSearch('');
            return false;
        }
    } 
    catch(ex) { }
    var characterCode;
    if(e && e.which)
    { 
        e = e;
        characterCode = e.which;
    }
    else
    {
        e = event;
        characterCode = e.keyCode;
    }

    if (characterCode == 13)
    {
        submitSearch('');    
        return false;
    }
    else
    {
        return true;
    }

}

function ShowPrivacyPolicy() {
   $(".privacyPolicy").load("/GenericContent.aspx?contentid=<%= gcidPrivacyPolicy %>", null, function(){
        var pos = $(".privacyPolicyLink").offset();
        var style = 'width:400px; height:500px; padding:20px; overflow:scroll; overflow-x:hidden; border:1px solid #555;background-color:#FFF;z-index:99999;cursor:pointer;position:absolute;top:'+(pos.top-10)+'px;left:'+(pos.left-86)+'px;';
        //$('.privacyPolicy').attr('style', style).show();            
        showWindow('.privacyPolicy', 'Privacy Policy', false, true);
   });       
}

function ddlCountries_OnChange(obj) {
    var country = $('option:selected', obj).val().toLowerCase();
    
    if(country == 'usa') {
        $('div.region').hide();
        $('#<%= ddlStates.ClientID %>').val('');
        $('div.state').show();
    } else {
        $('#Region').val('');
        $('div.region').show();
        $('div.state').hide();
    }
}

function InterestOptionAll_OnChange(obj) {
    var isChecked = $(obj).is(':checked');
    
    $('input:checkbox', '.interestOptions').each( function(){
        this.checked = isChecked;
    });
}    

function EmailSignUp_Click() {
    var errors = ValidateEmailSignUp();

    $('.errors', '#EmailSignUp').hide();
    $('#errorList', '#EmailSignUp').empty();
    
    if(errors != '') {
        $('#errorList', '#EmailSignUp').empty().append(errors);
        $('.errors', '#EmailSignUp').show();
    } else {
        EmailSignUp();
    }
}

function EmailSignUp() {
    var email = $('.emailSignupEmailAddress').val();
    var emailConfirm = $('.emailSignupConfirmEmailAddress').val();
    var firstName = $('.emailSignupFirstName').val();
    var lastName = $('.emailSignupLastName').val();
    var state = $('.emailSignupStates').val();
    var region = $('.emailSignupRegion').val();
    var country = $('option:selected', '.emailSignupCountries').val().toLowerCase();
    var emailFormat = $("input[name='emailFormat']:checked").val();
    var company = $('.emailSignupCompany').val();
    var address1 = $('.emailSignupAddress1').val();
    var address2 = $('.emailSignupAddress2').val();
    var city = $('.emailSignupCity').val();
    var postalCode = $('.emailSignupZipCode').val();
    var phoneNumber = $('.emailSignupPhone').val();
    var requestCatalog = $('#cbCatalogRequest').is(':checked');
    var interests = GrabEmailSignUpSelectedInterests();    
    
    if(emailFormat == 'html') {
        emailFormat = true;
    } else {
        emailFormat = false;
    }
        
    $.ajax({
        url: '/WebServices/EmailSignUp.asmx/SignUp',
        data: 'email='+email+'&firstname='+firstName+'&lastname='+lastName+'&state='+state+'&region='+region+'&country='+country+'&emailformat='+emailFormat+'&company='+company+'&address1='+address1+'&address2='+address2+'&city='+city+'&postalcode='+postalCode+'&phonenumber='+phoneNumber+'&interests='+interests+'&requestcatalog='+requestCatalog,
        type: 'GET',
        dataType: 'xml',
        timeout: 30000,
        error: function(){
            //debug('Error loading document types');
            //UnBlock('.productImage', 500);
        },
        success: function(xml){  
            $(xml).find('result').each(function(){
                var catalogSignUpResult = $('catalogSignUpResult', this).text();
                var emailSignUpResult = $('emailSignUpResult', this).text();
                var isSignedUp = $('isSignedUp', this).text();
                
                $('#fields').hide();
                $('.errors', '#EmailSignUp').hide();
                $('strong.emailEmailSignUp').html(email);                    
                $('.emailSignUpResults', '#EmailSignUp').empty().append(emailSignUpResult);
                $('#fields', '#EmailSignUp').hide();
                $('#Results', '#EmailSignUp').show();
            });
        }
    });    
}

function ValidateEmailSignUp() {
    var retval = '';
    var email = $('.emailSignupEmailAddress').val();
    var emailConfirm = $('.emailSignupConfirmEmailAddress').val();
    var firstName = $('.emailSignupFirstName').val();
    var lastName = $('.emailSignupLastName').val();
    var state = $('.emailSignupStates').val();
    var region = $('.emailSignupRegion').val();
    var country = $('option:selected', '.emailSignupCountries').val().toLowerCase();
    var emailFormat = $("input[name='emailFormat']:checked").val();
    var company = $('.emailSignupCompany').val();
    var address1 = $('.emailSignupAddress1').val();
    var address2 = $('.emailSignupAddress2').val();
    var city = $('.emailSignupCity').val();
    var postalCode = $('.emailSignupZipCode').val();
    var phoneNumber = $('.emailSignupPhone').val();
    var requestCatalog = $('#cbCatalogRequest').is(':checked');
    var interests = GrabEmailSignUpSelectedInterests();
    
    if(email == '') {
        retval += '<li>Email is required.</li>';
    } else if (!ValidateEmail(email)) {
        retval += '<li>Invalid email format.</li>';
    }
    
    if(emailConfirm == '') {
        retval += '<li>Email Confirmation is required.</li>';
    } else if (!ValidateEmail(emailConfirm)) {
        retval += '<li>Invalid Email Confirmation format.</li>';
    }
    
    if(email != emailConfirm) {
        retval += '<li>Email and Email Confirmation do not match.</li>';
    }
            
    if(firstName == '') {
        retval += '<li>First Name is required.</li>';
    }
    
    if(lastName == '') {
        retval += '<li>Last Name is required.</li>';
    }        
    
    if(country == 'usa') {
        if(state == '') {
            retval += '<li>State is required.</li>';
        }                
    } else {
        if(region == '') {
            retval += '<li>Region is required.</li>';
        }                
    }        
    
    if(emailFormat == null) {
        retval += '<li>Email Format is required.</li>';
    }
    
    if(interests == '') {
        retval += '<li>Please choose one or more interests.</li>';
    }
    
    if(requestCatalog) {
        if(address1 == '') {
            retval += '<li>Address is required.</li>';
        }                         
        
        if(city == '') {
            retval += '<li>City is required.</li>';
        }                      
        
        if(postalCode == '') {
            retval += '<li>Postal Code is required.</li>';
        } else if (!ValidateZipCode(postalCode)) {
            retval += '<li>Postal Code is invalid.</li>';
        }       
    }
    
    return retval;
}

function GrabEmailSignUpSelectedInterests() {
    var retval = '';
    
    $('input:checkbox', 'div.interests').each(function() {
        var id = $(this).parent().attr('interestID');
        if($(this).is(':checked')) {
            //alert(id);
            if(retval == '') {
                retval = id;
            } else {
                retval += '|' + id;
            }
        }
    }); 
    
    return retval;   
}
    
/* Helper Functions*/    
function showWindow(obj, theTitle, isModal, canClose) {
  new Boxy(obj, {title:theTitle, modal:isModal, closeable:canClose });
};
/* End Helper Functions */
