//jquery noconfict with other js library
jQuery.noConflict();

jQuery(function(){

    if(jQuery('#co-billing-form .control label').size() == 2){
        jQuery('#co-billing-form .control label').eq(0).html('Deliver to this address');
        jQuery('#co-billing-form .control label').eq(1).html('Deliver to a different address');
    }else if(jQuery('#co-billing-form .control label').size() == 3){
        jQuery('#co-billing-form .control label').eq(1).html('Deliver to this address');
        jQuery('#co-billing-form .control label').eq(2).html('Deliver to a different address'); 
    }
    
    
    
    //modFlatRate();
    //hideFlatRate();
    
    var bInterval = setInterval(function(){
        hideFlatRate();
    },100);
    
    function modFlatRate(){
        if( jQuery('#co-shipping-method-form #checkout-shipping-method-load .sp-methods dt').size() > 0){
            jQuery('#co-shipping-method-form #checkout-shipping-method-load .sp-methods dt').hide();
        }
        var FlatRate = jQuery('#co-shipping-method-form #checkout-shipping-method-load .sp-methods dd ul li label');
        if( FlatRate.size() > 0){
            var spanPrice = FlatRate.find('span').html();
            FlatRate.html('<div id="mod-flat-rate">Narrow Tree Nursery delivers trees, shrubs, plants and garden supplies ordered from NarrowTree.com directly to your home or project site. The delivery fee for online orders is a flat rate of <span class="price">' + spanPrice + '</span>, no matter how much you order or where you live in our delivery zone</div>');
            
            //FlatRate.append(', no matter how much you order or where you live in our delivery zone');
            //var FlatRateContent = FlatRate.html().replace('Fixed','Narrow Tree Nursery delivers trees, shrubs, plants and garden supplies ordered from NarrowTree.com directly to your home or project site. The delivery fee for online orders is a flat rate of ');

            //FlatRate.html(FlatRateContent);
        }
    }
    
    /*hide flat rate if customer get shipping free
        by default: system display all Flat Rate and Shipping Free
    */
    function hideFlatRate(){
        var freeChk = jQuery('#s_method_freeshipping_freeshipping');
        var flatChk = jQuery('#s_method_flatrate_flatrate');
        
        if(freeChk.size() > 0 && flatChk.size() > 0){
            freeChk.parents('dd').eq(0).hide();
            flatChk.parents('dd').eq(0).prev().andSelf().hide();
        } else {
            jQuery('#checkout-shipping-method-load dl dd').eq(0).hide();
        }
    }
    

    jQuery('.quick-access').prepend('<div class="header-contact" style="text-align: right; font-size: 11px !important; margin-top: 10px; margin-bottom: 10px;">'
            +'<span><a href="/contact"><b style="font-weight: bold;">Contact Us |</b>&nbsp<a href="mailto:info@narrowtree.com">info@narrowtree.com</a></span>'
            +'</div>');
    jQuery('head').append('<meta name="viewport" content="width=1040"/>');
    
    
    
    /*MOD ADD TO CART BUTTON: USING AJAX INSTEAD OF LINK TO KEEP CURRENT PAGE*/
    var button = jQuery('button.btn-cart');
    if(jQuery('#product_addtocart_form').size() > 0){//add to cart a grouped product (in grouped product detail page)
        button.removeAttr('onclick');
        button.click(function(){
            jQuery.ajax({
                url: jQuery('#product_addtocart_form').attr('action'),
                action:'post',
                data:jQuery('#product_addtocart_form').serialize(),
                dataType:'html',
                success : function(rs){
                    var messageUl = jQuery('ul.messages');
                    if(messageUl.size() > 0){
                        messageUl.remove();
                    }
                    jQuery('ul.messages', rs).prependTo('.product-essential');
                    
                    jQuery('div.top-cart').replaceWith(jQuery('div.top-cart', rs));
                    Enterprise.TopCart.initialize('topCartContent');
                    jQuery('div.top-cart li.item:last').addClass('last');
                }
            });
        });
    }else{//add to cart a simgle product or grouped product => override
        
        
        
        
        button.each(function(){
            var $this = jQuery(this);
            
            if ($this.parents('li.item').find('.regular-price').size() > 0) {//single product => usring ajax to add to shopping cart, show message and refresh cart quantity number
                //var onclickVal = $this.attr('onclick');
                var onclickVal = jQuery('<div>').append($this.clone()).remove().html();

                var checkUrl = onclickVal.substring(onclickVal.indexOf("('") + 2, onclickVal.indexOf("')"));
                $this.removeAttr('onclick');
                $this.click(function(){
                    jQuery.ajax({
                        url: checkUrl,
                        action:'get',
                        dataType:'html',
                        success : function(rs){
                            //jQuery('ul.messages', rs).prependTo('.product-essential');
                            var productName = $this.parents('li.item').find('h2.product-name a').text();
                            var messageUl = jQuery('ul.messages');
                            if(messageUl.size() > 0){
                                messageUl.remove();
                            }
                            jQuery('div.col-main').prepend('<ul class="messages"><li class="success-msg"><ul><li>' + productName + ' was added to your shopping cart.</li></ul></li></ul>');
                            
                            jQuery('div.top-cart').replaceWith(jQuery('div.top-cart', rs));
                            Enterprise.TopCart.initialize('topCartContent');
                            jQuery('div.top-cart li.item:last').addClass('last');
                        }
                    });
                });
            }
            
            /*
            
            */
        });
        
    
        
    }
    
    /*mod thumbnail behavior in product detail page*/
    var thumbLinks = jQuery('div.more-views ul li a');
    thumbLinks.removeAttr('onclick');
    thumbLinks.each(function(){ 
        jQuery(this).click(function(){
            try{
                var $a = jQuery(this);
                var thumbUrl = $a.find('img:eq(0)').attr('src');
                var largeUrl = thumbUrl.replace('thumbnail/48x','image/370x');
                var baseUrl = thumbUrl.replace('thumbnail/48x','image');
                
                //check larger img is larger than base img or not
                //to display zoom tool
                var largeImg = new Image();
                largeImg.src = largeUrl;
                
                var baseImg = new Image();
                baseImg.src = baseUrl;
                
                if(largeImg.width < baseImg.width || largeImg.height < baseImg.height){//display zoom
                    jQuery('.product-image').replaceWith('<a href="'+baseUrl+'" id="main-image" class="product-image" title="">'+
                                                    '<img width="370" height="370" alt="" src="'+largeUrl+'" title="">'+
                                                    '</a>');
                
                    $magejQuery('.product-image').jqzoom({
                        zoomType: 'reverse',//Values: standard, reverse
                        zoomWidth: 370,
                        zoomHeight: 370,
                        xOffset: 0,
                        yOffset: 0,
                        imageOpacity: 0.6,
                        title : false
                    });
                    
                    if(jQuery('.product-img-box .notice').size() > 0){
                        jQuery('.product-img-box .notice').text('Click on image to zoom');
                    }else{
                        jQuery('.product-image').after('<p class="notice">Click on image to zoom</p>');
                    }
                }else{//don't display zoom
                    jQuery('.product-image').replaceWith('<p class="product-image">'+
                                                    '<img width="370" height="370" title="" alt="" src="'+largeUrl+'">'+
                                                    '</p>');
                    if(jQuery('.product-img-box .notice').size() > 0){
                        jQuery('.product-img-box .notice').text('');
                    }else{
                        jQuery('.product-image').after('<p class="notice">Click on image to zoom</p>');
                    }
                    
                }
            }catch(e){
                //alert(e.message);
            }

        });
    });
    
    /*mod product detail information to display vertically*/
    jQuery('#collateral-tabs').css('height','auto');
    jQuery('#collateral-tabs dt.tab').attr('class','tab first active');
    jQuery('#collateral-tabs dd.tab-container').show();
    /*
    var arrDt = $$('#collateral-tabs dt.tab');
    for(var i = 0, i < arrDt.length, i++){
        arrDt[i].stopObserving('click');
    }
    */
    $$('#collateral-tabs dt.tab').each(function(item){
        item.stopObserving('click');
    });
    
    /*MOD PROCESS CHECKOUT START: adding zipcode validation, only allow shipping to Kansas or Missouri address*/
    //shipZip array and Shipping error message are defined in "footer links" static block
    
    jQuery('#billing\\:postcode').after('<div id="billing-zip-code-out" class="validation-advice" style="display:none; width: 380px; margin-right: 0px;">' + shippingErrorMsg + '</div>');
    jQuery('#checkout-step-billing').prepend('<ul id="billing-zip-code-error" class="messages" style="display: none;"><li class="error-msg"><ul><li>' + shippingErrorMsg + '</li></ul></li></ul>');
    jQuery('#billing\\:postcode').blur(function(){
        jQuery(this).nextAll('#billing-zip-code-out').hide();
    });
    
    jQuery('#checkout-step-billing #billing-buttons-container button').click(function(){
        var radUseFor = jQuery('#billing\\:use_for_shipping_yes');
        if(radUseFor.is(':checked')){//using billing address for shipping address => need to validate billing address
            var cboBillAdd = jQuery('#billing-address-select');
            var billZipCode = jQuery.trim(jQuery('#billing\\:postcode').val());
            if(cboBillAdd.size() == 0){//guest user
                if(billZipCode != '' && jQuery.inArray(billZipCode, shipZip) == -1){
                    showZipCodeError(jQuery('#billing\\:postcode'));
                    return false;
                }
                
            } else {//registered user
                if(cboBillAdd.val() == ''){//user insert new address
                    if(billZipCode != '' && jQuery.inArray(billZipCode, shipZip) == -1){
                        showZipCodeError(jQuery('#billing\\:postcode'));
                        return false;
                    }
                }else{
                    var shipZipFlag = false;
                    jQuery.each(shipZip, function(index, value){
                        if(cboBillAdd.find(':selected').text().indexOf(value + ',') >= 0){
                            shipZipFlag = true;
                            return false;
                        }
                    });
                    if(!shipZipFlag){
                        showZipCodeError(jQuery('#billing\\:postcode'));
                        return false;
                    }else{
                        hideZipCodeError(jQuery('#billing\\:postcode'));
                    }
                }
            }
        }
        hideZipCodeError(jQuery('#billing\\:postcode'));
        //alert("saving bill...");
        billing.save();
        
    });
    jQuery('#checkout-step-billing #billing-buttons-container button').removeAttr('onclick');

    function showZipCodeError(elm){
        jQuery('#billing-zip-code-error').hide();
        elm.removeClass('validation-failed').addClass('validation-passed');
        elm.nextAll('#billing-zip-code-out').hide();
        elm.parent().removeClass('validation-error').addClass('validation-passed');
        if (jQuery('#billing-address-select').size() == 0 || jQuery('#billing-address-select').val() == ''){
            elm.removeClass('validation-passed').addClass('validation-failed');
            elm.nextAll('#billing-zip-code-out').show();
            elm.parent().removeClass('validation-passed').addClass('validation-error');
        } else {
            jQuery('#billing-zip-code-error').show();
            
        }
        
        
    }
    
    function hideZipCodeError(elm){
        if (jQuery('#billing-address-select').val() == ''){
            elm.removeClass('validation-failed').addClass('validation-passed');
            elm.nextAll('#billing-zip-code-out').hide();
            elm.parent().removeClass('validation-error').addClass('validation-passed');
        } else {
            jQuery('#billing-zip-code-error').hide();
        }
        
    }
        
    jQuery('#shipping\\:postcode').after('<div id="shipping-zip-code-out" class="validation-advice" style="display:none; width: 380px; margin-right: 0px;">' + shippingErrorMsg + '</div>');
    jQuery('#checkout-step-shipping').prepend('<ul id="shipping-zip-code-error" class="messages" style="display: none;"><li class="error-msg"><ul><li>' + shippingErrorMsg + '</li></ul></li></ul>');
    jQuery('#shipping\\:postcode').blur(function(){
        jQuery(this).nextAll('#shipping-zip-code-out').hide();
    });
    
    jQuery('#checkout-step-shipping #shipping-buttons-container button').click(function(){
        var radUseFor = jQuery('#shipping\\:use_for_shipping_yes');
        
            var cboBillAdd = jQuery('#shipping-address-select');
            var billZipCode = jQuery.trim(jQuery('#shipping\\:postcode').val());
            
            if(cboBillAdd.size() == 0 || cboBillAdd.val() == ''){//user insert new address
                if(billZipCode != '' && jQuery.inArray(billZipCode, shipZip) == -1){
                    showZipCodeError2(jQuery('#shipping\\:postcode'));
                    return false;
                }
            }else{//user select exist address
                var shipZipFlag = false;
                jQuery.each(shipZip, function(index, value){
                    if(cboBillAdd.find(':selected').text().indexOf(value + ',') >= 0){
                        shipZipFlag = true;
                        return false;
                    }
                });
                if(!shipZipFlag){
                    showZipCodeError2(jQuery('#shipping\\:postcode'));
                    return false;
                }
            }
            
        
        hideZipCodeError2(jQuery('#shipping\\:postcode'));
        //alert("saving bill...");
        shipping.save();
        var sInterval = setInterval(function(){
            var FlatRate = jQuery('#co-shipping-method-form #checkout-shipping-method-load .sp-methods dd ul li label');
            if(FlatRate.size() > 0 && FlatRate.find('#mod-flat-rate').size() == 0){
                modFlatRate();
                clearInterval(sInterval);
            }
            
        },100);
    });
    jQuery('#checkout-step-shipping #shipping-buttons-container button').removeAttr('onclick');
    
    function showZipCodeError2(elm){
        jQuery('#shipping-zip-code-error').hide();
        elm.removeClass('validation-failed').addClass('validation-passed');
        elm.nextAll('#shipping-zip-code-out').hide();
        elm.parent().removeClass('validation-error').addClass('validation-passed');
        if (jQuery('#shipping-address-select').size() == 0 || jQuery('#shipping-address-select').val() == ''){
            elm.removeClass('validation-passed').addClass('validation-failed');
            elm.nextAll('#shipping-zip-code-out').show();
            elm.parent().removeClass('validation-passed').addClass('validation-error');
        } else {
            jQuery('#shipping-zip-code-error').show();
            
        }
    }
    
    function hideZipCodeError2(elm){
        if (jQuery('#shipping-address-select').val() == ''){
            elm.removeClass('validation-failed').addClass('validation-passed');
            elm.nextAll('#shipping-zip-code-out').hide();
            elm.parent().removeClass('validation-error').addClass('validation-passed');
        } else {
            jQuery('#shipping-zip-code-error').hide();
        }
    }
    /*MOD PROCESS CHECKOUT END: adding zipcode validation, only allow shipping to Kansas or Missouri address*/
    
    /*START MOD WHOLESALE PRICE*/
    jQuery('.regular-price .price').each(function(){
        var $this = jQuery(this);
        var $ul = $this.parent().parent().next('ul.product-pricing-grouped');
        if($ul.size() > 0){
            $this.css({'text-decoration':'line-through','color':'red'});
            $ul.css({'color':'#1E75B4','font-weight':'bold'});
            $ul.find('li').each(function(){
                var $li = jQuery(this);
                $li.html('Wholesale Price: <span>' + $li.find('span').text() + '</span>');
            });
        }
    });
    /*END MOD WHOLESALE PRICE*/
    
    jQuery('#nav li a.level-top').each(function(){
        jQuery(this).click(function(event){
            if(jQuery(this).next('ul.level0').size() > 0){
                return false;
            }
        });
    });
    
});

//override menu behavior to make this site runs on ipad
var lastClickItem = null;

if(navigator.userAgent.match(/iPad/i) != null){
    var mainNav = function () {
        var main = {
            obj_nav : $(arguments[0]) || $("nav"),
            settings : {
                show_delay : 0,
                hide_delay : 0,
                _ie6 : /MSIE 6.+Win/.test(navigator.userAgent),
                _ie7 : /MSIE 7.+Win/.test(navigator.userAgent)
            },
            init : function (obj, level) {
                obj.lists = obj.childElements();
                obj.lists.each(function (el, ind) {
                        main.handlNavElement(el);
                        if ((main.settings._ie6 || main.settings._ie7) && level) {
                            main.ieFixZIndex(el, ind, obj.lists.size());
                        }
                    });
                if (main.settings._ie6 && !level) {
                    document.execCommand("BackgroundImageCache", false, true);
                }
            },
            handlNavElement : function (list) {
                if (list !== undefined) {
                    list.onmouseover = function (clickEvent) {
                        //alert("over");
                        main.fireNavEvent(this, true, clickEvent);
                    };
                    list.onmouseout = function () {
                        main.fireNavEvent(this, false);
                    };
                    list.onclick = function (clickEvent) {
                        if(list.down('ul') != undefined && clickEvent.target.className.indexOf('level-top') != -1){
                            if(list == lastClickItem){
                                lastClickItem = list;
                            }else{
                                lastClickItem = list;
                                Event.stop(clickEvent);
                            }
                        }
                    };
                    if (list.down("ul")) {
                        main.init(list.down("ul"), true);
                    }
                }
            },
            ieFixZIndex : function (el, i, l) {
                if (el.tagName.toString().toLowerCase().indexOf("iframe") == -1) {
                    el.style.zIndex = l - i;
                } else {
                    el.onmouseover = "null";
                    el.onmouseout = "null";
                }
            },
            fireNavEvent : function (elm, ev, clickEvent) {//li
                if (ev) {
                    elm.addClassName("over");
                    elm.down("a").addClassName("over");
                    if (elm.childElements()[1]) {
                        main.show(elm.childElements()[1], clickEvent);
                    }
                } else {
                    elm.removeClassName("over");
                    elm.down("a").removeClassName("over");
                    if (elm.childElements()[1]) {
                        main.hide(elm.childElements()[1]);
                    }
                }
            },
            show : function (sub_elm, clickEvent) {//ul
                if (sub_elm.hide_time_id) {
                    clearTimeout(sub_elm.hide_time_id);
                }
                sub_elm.show_time_id = setTimeout(function () {
                            if (!sub_elm.hasClassName("shown-sub")) {
                                sub_elm.addClassName("shown-sub");
                                
                            }
                        }, main.settings.show_delay);
            },
            hide : function (sub_elm) {
                if (sub_elm.show_time_id) {
                    clearTimeout(sub_elm.show_time_id);
                }
                sub_elm.hide_time_id = setTimeout(function () {
                            if (sub_elm.hasClassName("shown-sub")) {
                                sub_elm.removeClassName("shown-sub");
                            }
                        }, main.settings.hide_delay);
            }
        };
        if (arguments[1]) {
            main.settings = Object.extend(main.settings, arguments[1]);
        }
        if (main.obj_nav) {
            main.init(main.obj_nav, false);
        }
    };
}


