
//  ====================================================================================================
//  JavaScript Error Reporting (comment out for launch)
//  ====================================================================================================

//window.onerror = function(desc, page, line, chr) {
//    alert('JavaScript error occurred! \n'
//        + '\nError description: \t' + desc
//        + '\nPage address:      \t' + page
//        + '\nLine number:       \t' + line
//        );
//}

//  ====================================================================================================
//  JavaScript Error Suppression
//  ====================================================================================================

//    function silentErrorHandler() {return true;}
//    window.onerror=silentErrorHandler;

//  ====================================================================================================
//  Onload Events
//  ====================================================================================================

    $(window).ready(function(){ WireEvents() });

    // Bind the CDBImageLoader to the load event of the page
    $(window).bind('load', function() {
       var timeout = setTimeout(function() { CDBImageLoader() }, 100);
    });   

    $(window).bind('resize', function() {
       LoadImagesAboveFold();
    });   

    // Load any images that have the class "loader" and do not have a "src" currently set into the browser
    function CDBImageLoader()
    {
        $("img.loader").each(function() {
            var $image = $(this);
            if ($image.attr("src") == null || $image.attr("src") == "" && $image.attr("title").length > 0) {
                $image
                    .attr("src", $image.attr("title"))
                    .attr("title", "")
                    .show();
            }   // if
        });
        
    }   // CDBImageLoader()

    function BelowTheFold(image, threshold) {
        var fold = $(window).height() + $(window).scrollTop();
        return (fold <= $(image).offset().top - threshold);
    }
    function LoadImagesAboveFold()
    {
        //  Load any images that are currently above the fold
        $("img.lazy").each(function() {
            if (!BelowTheFold($(this), 0)) {
                $(this).attr("src", $(this).attr("title")).attr("title", "").removeClass("lazy");
            }
        });
    }
    function BindScrollEvent()
    {
        $(window).scroll(function() { LoadImagesAboveFold(); });
    }
    
    function ConfigureJPlayer()
    {
        if ($("#jquery_jplayer").length > 0)
        {
            if (DetectAndroid())
            {                         
	        }   // if
            else
            {
	            $("#jquery_jplayer").jPlayer({
		            ready: function () {
		            },
		            volume: 100,
		            oggSupport: false,
		            swfPath: "/scripts"
	            })
	            .jPlayer("onSoundComplete", function() {
	            });        
            }   // else
        
        }   // if
    }   // ConfigureJPlayer()


    //**************************
    // Detects if the current device is an Android OS-based device.
    function DetectAndroid()
    {
        var agent = navigator.userAgent.toLowerCase();

        if (agent.indexOf("android") > -1)
            return true;
        else
            return false;
    }



    function WireEvents() 
    {   
        LoadImagesAboveFold();
        BindScrollEvent();

        ConfigureJPlayer();

        // bind the max length on textareas
        $(".textarea-300").keypress(function(event){  
            var key = event.which;  
            if(key >= 33 || key == 13) 
            {  
                if(this.value.length >= 300) { event.preventDefault(); } 
            }
        });  

        // Make sure these events has not already been bound
        if ( $("#boundPageEvents").attr("title") == "NO" )
        {

            // bind the focus/blur effects for selected input elements
            BindInputEvents();
         
            
            // Set the heights of the overlay links according to their parent size
            SetOverlayLinkHeight();

            // Search Button Hover Image Swap
            $(".search-button").hover(
                function() { $(this).attr("src", "/Images/Buttons/button-search_f2.jpg"); },
                function() { $(this).attr("src", "/Images/Buttons/button-search.jpg"); }
            );

            // Search Box Flocus/Blur Events
            $(".search-box").focus(function () {
                if ( $(this).val() == "type your search here..." ) { $(this).val("").css("color","#000"); }
            });
            $(".search-box").blur(function () {
                if ( $(this).val() == "" ) { $(this).css("color","#0D1116").val("type your search here..."); }
            });

            //  ====================================================================================================
            //  Pagination click event to display a loading image in the place of the clicked button
            //  ====================================================================================================

//            $(".pagination a").click(function() {
//                if (!($(this).hasClass("active")) && $(this).attr("disabled") != "disabled") {
//                    $(this).css("display", "none");
//                    if ($(this).hasClass("previous-link") || $(this).hasClass("next-link")) {
//                        $(this).parent().html("").append("<div style='width:62px; text-align:center; margin:auto;'><img src='/images/loading-pagination.gif' /></div>");
//                    }
//                    else {
//                        $(this).parent().html("").append("<div style='width:33px; text-align:center; margin:auto;'><img src='/images/loading-pagination.gif' /></div>");
//                    }
//                }
//                $("#boundPageEvents_Pager").attr("title", "NO");
//            });

            // Block these events from getting bound by any other content panels on the page
            $("#boundPageEvents").attr("title","YES");

        }

		// Call the page's events function
		PageEvents();
    }

    //  ====================================================================================================
    //  Preload Images
    //  ====================================================================================================

        jQuery.preloadImages = function(arr) {
            for (var i = 0; i < arr.length; i++) {
                jQuery("<img>").attr("src", arr[i]);
            }
        }

    //  ====================================================================================================
    //  Input Bindings
    //  ====================================================================================================

        function BindInputEvents() {
            $(".textbox").focus(function() {
                $(this).css("color", "#669").css("borderColor", "#aaa");
            });

            $(".textbox").blur(function() {
                $(this).css("color", "#666").css("borderColor", "#DDD");
            });
        }


    //  ====================================================================================================
    //  Set The height of the overlay links to their parent's height (ie6 bug)
    //  ====================================================================================================

        function SetOverlayLinkHeight() {
            $("#common-pages .overlay-link").each(function() {
                $(this).height($(this).parent().height() + 30);
            });
        }



    //  Form Validation Functions
    //  ====================================================================================================

    function checkReviewsForm()
    {
        var returnValue = true;
        
        if ( $(".review-name").val().trim() == "" ) { $(".error-review-name").css("display","block"); returnValue = false; }
        else{ $(".error-review-name").css("display","none"); }
        
        if ( $(".review-title").val().trim() == "" ) { $(".error-review-title").css("display","block"); returnValue = false; }
        else{ $(".error-review-title").css("display","none"); }
        
        if ( $(".review-rating").val().trim() == "0" ) {  $(".error-review-rating").css("display","block"); returnValue = false; }
        else{ $(".error-review-rating").css("display","none"); }
        
        if ( $(".textarea").val().trim() == "" ) { $(".error-review-text").css("display","block"); returnValue = false; }
        else { $(".error-review-text").css("display", "none"); }
        
        return returnValue;
    }
    
    function checkRedeemForm() {
        var returnValue = true;

        if ($(".local-input").val() == "" || $(".local-input").val() == "XXXXXX-XXXXXX") {
            $("#divRequired").css("display", "block");
            returnValue = false;
        }
        else {
            $("#divRequired").css("display", "none");
        }

        return returnValue;
    }


    function checkRequiredFields(myPops)
    {
        var returnValue = true;

        // check required fields
        $(myPops).parent().find(".req-field").each(function() {
            if ($(this).val().trim() == "") {
                $(this).parent().find(".required").css("display", "block");
                $(this).parent().addClass("failed");
                returnValue = false;
            }
            else {
                $(this).parent().find(".required").css("display", "none");
                $(this).parent().removeClass("failed");
            }
        });

        // check for a drop down selection
        $(myPops).parent().find(".req-selection").each(function() {
            if ($(this).val().trim() == "" || $(this).val() == "0") {
                $(this).parent().find(".required").css("display", "block");
                $(this).parent().addClass("failed");
                returnValue = false;
            }
            else {
                $(this).parent().find(".required").css("display", "none");
                $(this).parent().removeClass("failed");
            }
        });


        // check required fields
        $(myPops).parent().find(".req-month").each(function() {
            if (($(this).val()) == "" || ($(myPops).parent().find(".req-year").val() == "")) {
                $(this).parent().find(".required").css("display", "block");
                $(this).parent().addClass("failed");
                returnValue = false;
            }
            else {
                $(this).parent().find(".required").css("display", "none");
                $(this).parent().removeClass("failed");
            }
        });

        $(myPops).parent().find(".req-email").each(function() {
            
            var isEmail = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($(this).val().trim());

            if (!isEmail || $(this).val().trim() == "") {
                $(this).parent().find(".required").css("display", "block");
                $(this).parent().addClass("failed");
                returnValue = false;
            }
            else {
                $(this).parent().find(".required").css("display", "none");
                $(this).parent().removeClass("failed");
            }
        });
        
        // check zipcode
        $(myPops).parent().find(".req-zipcode").each( function() {
            if ( $(this).val() == "" ) {
                $(this).parent().find(".required").text("please enter zip/postal code.");
                $(this).parent().find(".required").css("display", "block"); 
                $(this).parent().addClass("failed");
                returnValue = false; 
            }
            else {
                if ($(this).parent().find(".zip-validator").css("visibility") == "visible")
                {
                    $(this).parent().find(".required").text("please enter zip/postal code in the correct format.");
                    $(this).parent().find(".required").css("display", "block");
                    $(this).parent().find(".zip-validator").css("display", "none")
                    $(this).parent().addClass("failed");
                    returnValue = false;
                }
                else { 
                    $(this).parent().find(".required").css("display","none"); 
                    $(this).parent().removeClass("failed"); 
                }
            }

        });

        // check phone number
//        $(myPops).parent().find(".req-phone").each(function() {
//            var isPhone = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/i.test($(this).val());

//            if (!isPhone || $(this).val() == "") {
//                $(this).parent().find(".required").css("display", "block");
//                $(this).parent().addClass("failed");
//                returnValue = false;
//            }
//            else {
//                $(this).parent().find(".required").css("display", "none");
//                $(this).parent().removeClass("failed");
//            }
//        });

        // check cvv
        $(myPops).parent().find(".req-cvv").each( function() {

            var isNumber = /^\d+$/.test($(this).val());

            if (!isNumber || $(this).val().length < 3 || $(this).val().length > 4) {
                $(this).parent().find(".required").css("display","block"); 
                $(this).parent().addClass("failed");
                returnValue = false; 
            }
            else { 
                $(this).parent().find(".required").css("display","none"); 
                $(this).parent().removeClass("failed"); 
            }
        });

        // check credit card
        $(myPops).parent().find(".req-creditcard").each(function() {

            var passLuhn = true;
            var value = $(this).val();

            // accept only digits and dashes
            if (/[^0-9-]+/.test(value)) {
                passLuhn = false;
            }
            else {
                var nCheck = 0,
			                nDigit = 0,
			                bEven = false;

                value = value.replace(/\D/g, "");

                for (n = value.length - 1; n >= 0; n--) {
                    var cDigit = value.charAt(n);
                    var nDigit = parseInt(cDigit, 10);
                    if (bEven) {
                        if ((nDigit *= 2) > 9)
                            nDigit -= 9;
                    }
                    nCheck += nDigit;
                    bEven = !bEven;
                }

                passLuhn = ((nCheck % 10) == 0) ? true : false;
            }

            if (!passLuhn || value.length < 1) {
                $(this).parent().find(".required").css("display", "block");
                $(this).parent().addClass("failed");
                returnValue = false;
            }
            else {
                $(this).parent().find(".required").css("display", "none");
                $(this).parent().removeClass("failed");
            }
        });

        // check passwords
        $(myPops).parent().find(".req-password1").each(function() {
            if ($(this).val().length < 8) {
                $(this).parent().find(".required").css("display", "block").text("your password must be at least 8 characters.");
                $(this).parent().addClass("failed");
                $(myPops).parent().find(".req-password2").parent().find(".required").css("display", "none");
                $(myPops).parent().find(".req-password2").parent().removeClass("failed");
                returnValue = false;
            }
            else if ($(this).val().length >= 8 && $(myPops).parent().find(".req-password2").val().length == 0)
            {
                $(this).parent().find(".required").css("display", "none");
                $(this).parent().removeClass("failed");
                $(myPops).parent().find(".req-password2").parent().find(".required").css("display", "block");
                $(myPops).parent().find(".req-password2").parent().addClass("failed")
                returnValue = false;
            }
            else if ($(this).val() != $(myPops).parent().find(".req-password2").val())
            {
                $(this).parent().find(".required").css("display", "block").text("your passwords don't match.");
                $(this).parent().addClass("failed");
                $(myPops).parent().find(".req-password2").parent().find(".required").css("display", "block").text("your passwords don't match.");
                $(myPops).parent().find(".req-password2").parent().addClass("failed")
                returnValue = false;
            }
            else {
                $(this).parent().find(".required").css("display", "none");
                $(this).parent().removeClass("failed");
                $(myPops).parent().find(".req-password2").parent().find(".required").css("display", "none");
                $(myPops).parent().find(".req-password2").parent().removeClass("failed");
            }
        });

        // fix to show/hie resiter button on registration page
        if (($(".newadd-button").length > 0) && returnValue)
        {
            $(".newadd-button").css("display", "none");
            $(".submit-label").css("display", "inline");
        }
       
        return returnValue;
    }
