/* <!-- AjaxPro --> */



var AjaxPro = function () {



var _config = {

    message: '',

    location: 'center',

    opacity: 0.95,

    

    isShoppingCart: 1,

    isCompare: 1,

    isWishlist: 1,



    hasNoticeForm: 1,

    hasShoppingCartForm: 1,

    hasCompareForm: 1,

    hasWishlistForm: 1,



    handles : [],

    isLoggin: 0,

    baseUrl: '',

    secureUrl: '',



    hasDeleteCartConfirm: 1,

    hasDeleteCompareConfirm: 1,

    hasDeleteWishlistConfirm: 1,



    removeCartItemMessage     : '',

    removeCompareItemMessage  : '',

    removeCompareClearMessage : '',

    removeWishlistItemMessage : ''

};



function _getPosition()

{   

    // 'bottom', 'center'

    switch (_config.location) {

        case 'top':

            var left = document.viewport.getWidth() / 2 - 100;

            var top = 10;

            

            break;

        case 'bottom':

            left = document.viewport.getWidth() / 2 - 100;

            top = document.viewport.getHeight() - 150;

            break;

        case 'center':default:

            left = document.viewport.getWidth() / 2 - 100;

            top = document.viewport.getHeight() / 2 - 150;

            break;

    }

    //fix IE6 position:fixed

    Prototype.Browser.IE6 = Prototype.Browser.IE && 

        parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE") + 5)) == 6;

    if (Prototype.Browser.IE6) {

        top = document.viewport.getScrollOffsets().top + document.viewport.getHeight() / 2 - 150;

    }

    return {'top': top + 'px', 'left':left + 'px'};

}

function _hideProgress()

{

    $('ajaxpro-spinner').hide();

}

function _showProgress()

{

    _hideProgress();

    $('ajaxpro-spinner').setStyle(_getPosition()).show();

}

function _showMessage(id, message)

{

    message = message || '';

    var element = $(id);

    element.setStyle(_getPosition());

    element.select('.ajaxpro-message').invoke('update', message);

//  element.removeClassName('no-display')

    element.setStyle('');

    element.setOpacity(_config.opacity);

    element.show();

}

function _parseResponse(response)

{

    if (response == null) {

        window.location.reload();

    }



    if (response.redirectUrl) { //redirectUrl use like error flag :(((

        if (_config.hasNoticeForm && response.message) {

            _showMessage('ajaxpro-notice-form', response.message);

//            $('ajaxpro-notice-form').select('.ajaxpro-action-button').each(function(element){

//                element.setAttribute('href', response.redirectUrl);

//            });

        } else {

    if(response.message.lenght) {alert(response.message)};

            window.location.href = response.redirectUrl;

        }

    }

    //shopping cart blocks

    if (response.topLinkCart) {

        $$('.top-link-cart').invoke('replace', response.topLinkCart);

        if (response.message && _config.hasShoppingCartForm) {

            _showMessage('ajaxpro-addtocart-form', response.message);

        }



    }

    if (response.miniCart || response.miniCart == "") {

        $$('.block-cart').invoke('replace', response.miniCart);

    }

   if (response.headerCart || response.headerCart == "") {
      $('header-cart-wraper').update(response.headerCart);
   }


//    if (response.checkoutCart) {

//        $$('.col-main').invoke('update', response.checkoutCart);

//    }

    if (response.shoppingCartTable) {

        $('shopping-cart-table').replace(response.shoppingCartTable);

    }

    if (response.checkoutCartTotals) {

        $('shopping-cart-totals-table').replace(response.checkoutCartTotals);

    }

    //compare blocks

    if (response.compareSideBar || response.compareSideBar == "") {

        $$('.block-compare').invoke('replace', response.compareSideBar);

        if (response.message && _config.hasCompareForm) {

            _showMessage('ajaxpro-addtocompare-form', response.message);

        }

    }

    if (response.rightReportsProductCompared || response.rightReportsProductCompared == "") {

        $$('.block-compared').invoke('replace', response.rightReportsProductCompared);

    }

    // wishlist blocks

    if (response.topLinkWishlist) {



        //  

        $$('ul.links a').each(function(el){

            if(el.href.match(/.*\/wishlist\/$/)) {

                el.up().update(response.topLinkWishlist);

            }

        });

//        $$('.top-link-wishlist').invoke('replace', response.topLinkWishlist);

//        if (response.message && _config.hasWishlistForm) {

//            _showMessage('ajaxpro-addtowishlist-form', response.message);

//        }

    }



    if (response.wishlistSideBar || response.wishlistSideBar == "") {



        $$('.block-wishlist').invoke('replace', response.wishlistSideBar);

    }

    if (response.customerWishlist) {

        $$('.col-main').invoke('update', response.customerWishlist);

    }



//    debugger;

//    //custom product

    if (response.productView) {

        $('ajaxpro-addcustomproduct-view').update(response.productView);

        _showMessage('ajaxpro-addcustomproduct-form', response.message);

//        debugger;

//        AjaxPro.redefineEvent.delay(0.5);

    }

}

function _showEffect(url) {

    var cssClass = false;

    if (url.search('/checkout/cart') != -1) {

        cssClass = '.block-cart';

    }

    if (url.search('/catalog/product_compare') != -1) {

        cssClass = '.block-compare';

        $$('.block-compared').each(function(element){

            element.setOpacity(0.5);

        });

    }

    if (url.search('/wishlist/index') != -1) {

        cssClass = '.block-wishlist';

    }

    if (cssClass) {

        $$(cssClass).each(function(element){

            element.setOpacity(0.5);

        });

    }

}

function _hideEffect(url) {

    var cssClass = false;

    if (url.search('/checkout/cart') != -1) {

        cssClass = '.block-cart';

    }

    if (url.search('/catalog/product_compare') != -1) {

        cssClass = '.mini-compare-products';

    }

    if (url.search('/wishlist/index') != -1) {

        cssClass = '.mini-wishlist';

    }

    if (cssClass) {

        $$(cssClass).each(function(element){

            element.setOpacity(1);

        });

    }

}

return {

    init: function(config) {

        Object.extend(_config, config);

    },

    onReady: function() {

        //add loading spinner

        var spinner = new Element('div', {'id': 'ajaxpro-spinner'});

        spinner.update('<p class="ajaxpro-message">' + _config.message + '</p>');

        document.body.appendChild(spinner.hide().setOpacity(_config.opacity));



        /**

         * redefine setLocation function

         */

        setLocation = function (url)

        {

            if (_config.isShoppingCart && url.search('checkout/cart/add') != -1

                && AjaxPro.request(url + 'ajaxpro/1', 'get')) {

                //Event.stop();

                return false;

            }

            if (_config.isWishlist && url.search('wishlist/index/cart') != -1

                && AjaxPro.request(url + 'ajaxpro/1', 'get')) {

                //Event.stop();

                return false;

            }

            if (_config.isShoppingCart && url.search('ajaxpro/product/view') != -1

                && AjaxPro.request(url + 'ajaxpro/1', 'get')) {

                //Event.stop();

                return false;

            }



            window.location.href = url;

        }

        

        AjaxPro.redefineEvent();



        //add event hide form message

        $$('.ajaxpro-continue-button').each(function(element){

            element.observe('click', function(event) {

                Event.stop(event);

                var el = Event.element(event);

                // while(el.tagName != 'A') {

                //     el = el.up();

                //}

                el.up('div').hide();

    //          Event.element(event).up().addClassName('no-display');

                return false;

            });

        });

        $$('.ajaxpro-action-button').each(function(element){

            element.observe('click', function(event) {

                Event.element(event).up().hide();

                return false;

            });

        });

    },

    /**

     * request function

     */

    request :function (url, method)

    {

        var responseStatus = true;

        var requestMethod = method || 'post';

        

        var currentUrl = window.location.href;

        var isBaseUrl = (0 === currentUrl.indexOf(_config.baseUrl));

        var isRequestBaseUrl = (0 === url.indexOf(_config.baseUrl));

        if (isBaseUrl && !isRequestBaseUrl) {

            url = url.replace(_config.secureUrl, _config.baseUrl);

        } else if (!isBaseUrl && isRequestBaseUrl) {

            url = url.replace(_config.baseUrl, _config.secureUrl);

        }



        if (typeof _config.handles.toJSON === "function") {

            var handles = _config.handles.toJSON();

        } else {

            var handles = JSON.stringify(_config.handles);

        }

		

        new Ajax.Request(url, {

            parameters: {'handles': handles}, 

            method: requestMethod,

            onLoading: function(transport) {

                _showProgress();

                

                _showEffect(url);

            },



            onComplete: function(transport) {

                var response = transport.responseJSON;

                if (200 != transport.status) {

                    responseStatus = false;

                    _hideProgress();

                    return false;

                }

                _parseResponse(response);

                _hideProgress();

                AjaxPro.redefineEvent.delay(0.5);

                _hideEffect(url);



                return false;

            }

        });

        return responseStatus;

    },

    redefineEvent: function()

    {

        /**

         * redeclare submit form function on product page

         *  add product action checkout/cart/add

         */

        if(typeof productAddToCartForm != 'undefined' && _config.isShoppingCart) {

            productAddToCartForm.submit = function() {

                var url = this.form.action;

                var isUploadFile = $(this.form).select('input[type=file]').length;

                if (isUploadFile) {

                    template = '<iframe id="product_addtocart_form_frame" name="product_addtocart_form_frame" style="width:0; height:0; border:0;display:none;"><\/iframe>';

                    Element.insert($('product_addtocart_form'), {after: template});

                    this.form.setAttribute('target', 'product_addtocart_form_frame');

                    //add product

                    this.form.submit();



                    var interval = window.setInterval(function() {

                        var isAfterSubmit = $$('#product_addtocart_form_frame', 'body').length > 1 ? true : false;

                        if(isAfterSubmit) {

                            AjaxPro.request(url + '?ajaxpro=1&onlyblocks=1');

                            Element.remove($('product_addtocart_form_frame'));

                            window.clearInterval(interval);

                        }

                    }, 1000);

                    this.form.removeAttribute('target');

                    return false;

                }

                var params = this.form.serialize();                

                if(this.validator && this.validator.validate()){

                    if (!AjaxPro.request(url + '?' + params  + '&ajaxpro=1')){

                        this.form.submit();

                    }

                    if (el = $('ajaxpro-addcustomproduct-form')) {

                        el.hide();

                    }

                }

                

                return false;

            }

			if($('qty')){

				$('qty').observe('keypress', function(event){

					if (13 === event.keyCode) {

						Event.stop(event);

						productAddToCartForm.submit();

					}

				});

			}

        }

        /**

         * redeclare submit form function on shopping cart page

         * update action checkout/cart/updatePost

         */

        var shoppingCartTable = $('shopping-cart-table');

        if (shoppingCartTable && _config.isShoppingCart) {

            var shoppingCartForm = shoppingCartTable.up('form');

            if(typeof shoppingCartForm != 'undefined'){

                shoppingCartForm.observe('submit', function(event) {

                    Event.stop(event);

                    var params = Event.element(event).serialize();

                    var url = Event.element(event).action;

                    if (!AjaxPro.request(url + '?' + params  + '&ajaxpro=1')){

                        Event.element(event).submit();

                    }

                    return false;

                });

            }

        }

        /**

         * get all page link and add redeclare his onclick event

         *

         */

        $$('a').each(function(element){



            var url = element.getAttribute('href');

//            var onclickHandler = element.getAttribute('onclick');



            if (url == '#' && _config.isShoppingCart)

            {

                var onclickHandler = element.getAttribute('onclick');

                if (

                    onclickHandler

                    && typeof onclickHandler == 'string'

                    && onclickHandler != ''

                    && onclickHandler.search('setLocation') != -1

                    && onclickHandler.search('checkout/cart/add') != -1

                ) {

                    

                    element.stopObserving('click');

                    element.observe('click', function(event) {

                        Event.stop(event);

                    });

                }

            }

            confirmation = true;

            if (url && _config.isShoppingCart

                && url.search('checkout/cart/delete') != -1)

            {

                element.stopObserving('click');

                element.setAttribute('onclick', '');

                element.observe('click', function(event) {

                    Event.stop(event);

                    if (_config.hasDeleteCartConfirm) {

                        confirmation = confirm(_config.removeCartItemMessage);

                        if(!confirmation) {return false;}

                    }

                    AjaxPro.request(url + 'ajaxpro/1', 'get');

                    return false;

                });

                return false;

            }

            //if enabled compare

            if (url && _config.isCompare &&

                ((url.search('catalog/product_compare/add') != -1)

                || (url.search('catalog/product_compare/remove') != -1)

                || (url.search('catalog/product_compare/clear') != -1)

                ))

            {

                element.stopObserving('click');



                if (url.search('catalog/product_compare/remove') != -1) {

                    element.setAttribute('onclick', '');

                }



                if (url.search('catalog/product_compare/clear') != -1) {

                    element.setAttribute('onclick', '');

                }



                element.observe('click', function(event) {

                    Event.stop(event);

                    if (_config.hasDeleteCompareConfirm) {

                        if (url.search('catalog/product_compare/remove') != -1) {

                            confirmation = confirm(_config.removeCompareItemMessage);

                        }

                        if (url.search('catalog/product_compare/clear') != -1) {

                            confirmation = confirm(_config.removeCompareClearMessage);

                        }

                        if(!confirmation) {return false;}

                    }

                    AjaxPro.request(url + 'ajaxpro/1', 'get');

                    return false;

                });

                return false;

            }

            //if enabled wishlist

            if (url && _config.isWishlist &&

                ((url.search('wishlist/index/add') != -1)

                ||(url.search('wishlist/index/remove') != -1)

//                ||(url.search('wishlist/index/cart') != -1)

                ))

            {

                element.stopObserving('click');

                if (url.search('wishlist/index/remove') != -1) {

                    element.setAttribute('onclick', '');

                }

                element.observe('click', function(event) {

                    Event.stop(event);

                    if (_config.hasDeleteWishlistConfirm) {

                        if (url.search('wishlist/index/remove') != -1) {

                            confirmation = confirm(_config.removeWishlistItemMessage);

                        }

                        if(!confirmation) {return false;}

                    }

                    if (!_config.isLoggin) {

                        window.location.href = _config.baseUrl + 'customer/account/login';

                    }



                    AjaxPro.request(url + 'ajaxpro/1', 'get');

                    return false;

                });

                return false;

            }



        });

    }

    }

}();



//onReady

if (Prototype.Browser.IE) {

    Event.observe(window, 'load', function(){ //KB927917 fix

        AjaxPro.onReady();

    });

} else {

    document.observe("dom:loaded", function(){

        AjaxPro.onReady();

    });

}


