/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var SearchAjaxForm = Class.create(VarienForm, {

    initialize: function($super, formId, firstFieldFocus, container, autocomplete){
        $super(formId, firstFieldFocus);
        this.validator = new Validation(this.form, {
            onSubmit: false
        });

        this.autocomplete = autocomplete || {};
        this._initAutocomplete();
        this.form.observe('submit', this._submit.bind(this));
        this.ajaxcontainer = $(container);
    },

    _initAutocomplete: function(){
        if(this.autocomplete.fields && this.autocomplete.fields.length > 0){
            var i = 0;
            for(i=0; i < this.autocomplete.fields.length; i++){
                var field = $(this.autocomplete.fields[i].id);
                new Ajax.Autocompleter(
                    field,
                    $(this.autocomplete.fields[i].dest),
                    this.autocomplete.fields[i].url,
                    {
                        paramName: field.name,
                        method: 'get',
                        minChars: 2,
                        updateElement: function(element){
                            if(element.title){
                                field.value = element.title;
                            }
                        },
                        onShow : function(element, update) {
                            if(!update.style.position || update.style.position=='absolute') {
                                update.style.position = 'absolute';
                                Position.clone(element, update, {
                                    setHeight: false,
                                    offsetTop: element.offsetHeight
                                });
                            }
                            Effect.Appear(update,{
                                duration:0
                            });
                        }

                    }
                    );
            }
        }
    },

    // redefine the speak method
    _submit: function($super, event) {
        $('first-form').hide();
        $('popularcharities').hide();
        $('second-form').show();
        $('results_container').show();
        $('starover').show();
        $('charity_locator_title').update('Narrow your results');
        $('charitylocator_simplesearch_results_container').update('Please wait...<img src="/skin/frontend/enterprise/giftsthatgive/images/ajax-loader.gif"/>');
        if(this.validator && this.validator.validate()){
            //this.form.submit();
            new Ajax.Request(this.form.action, {
                method:        "get",
                parameters:    this.form.serialize(),
                onSuccess:     this.onSuccess.bind(this)
            });
        }
        event.stop();
        return false;
    },

    _selectAutocompleteItem : function(element){
        if(element.title){
            this.field.value = element.title;
        }
    //event.stop();
    //this.form.submit();
    },

    onSuccess: function(transport){
        var response = transport.responseText;
        this.ajaxcontainer.update(response);
    },

    onComplete: function(transport){

    }
});

if (!window.GTG)
    var GTG = new Object();

GTG.searchForm = Class.create({
    initialize : function(form, field, emptyText){
        this.form   = $(form);
        this.field  = $(field);
        this.emptyText = emptyText;

        Event.observe(this.form, 'submit', this.submit.bind(this));
        Event.observe(this.field, 'focus', this.focus.bind(this));
        Event.observe(this.field, 'blur', this.blur.bind(this));
        this.blur();
    },

    submit : function(event){
        if (this.field.value == this.emptyText || this.field.value == ''){
            Event.stop(event);
            return false;
        }
        openLocatorWindow(this.form.action+"?"+this.form.serialize());
        event.stop();
    //return true;
    },

    focus : function(event){
        if(this.field.value==this.emptyText){
            this.field.value='';
        }

    },

    blur : function(event){
        if(this.field.value==''){
            this.field.value=this.emptyText;
        }
    },

    initAutocomplete : function(url, destinationElement){
        new Ajax.Autocompleter(
            this.field,
            destinationElement,
            url,
            {
                paramName: this.field.name,
                method: 'get',
                minChars: 2,
                updateElement: this._selectAutocompleteItem.bind(this),
                onShow : function(element, update) {
                    if(!update.style.position || update.style.position=='absolute') {
                        update.style.position = 'absolute';
                        Position.clone(element, update, {
                            setHeight: false,
                            offsetTop: element.offsetHeight
                        });
                    }
                    Effect.Appear(update,{
                        duration:0
                    });
                }

            }
            );
    },

    _selectAutocompleteItem : function(element){
        if(element.title){
            this.field.value = element.title;
        }
        openLocatorWindow(this.form.action+"?"+this.form.serialize());
    //event.stop();
    //this.form.submit();
    }
});

function updateSearchPagerLinks(){
    $$('#gtg_charities_locator_container #results_container div.pagination div.pages ol li a,#charities_locator #charitylocator_simplesearch_results_container div.pagination div.pages ol li a').each(function(item){
        item.observe('click', function(event){
            new Ajax.Request(this.href, {
                method:        "get",
                onSuccess:     function(transport){
                    var response = transport.responseText;
                    if($$('#gtg_charities_locator_container #results_container').length==1){
                        $$('#gtg_charities_locator_container #results_container')[0].update(response);
                    }else{
                        $$('#charities_locator #charitylocator_simplesearch_results_container')[0].update(response);
                    }
                }
            });
            event.stop();
        });
    });

    /*$$('#gtg_charities_locator_container #results_container div.pagination div.limiter select').each(function(item){
        item.onchange = null;
        item.observe('change', function(event){
            new Ajax.Request(this.value, {
                method:        "get",
                onSuccess:     function(transport){
                    var response = transport.responseText;
                    $$('#gtg_charities_locator_container #results_container')[0].update(response);
                }
            });
            event.stop();
        });
    });*/
    $$('.customPaginator').each(function(item){
        item.observe('click', function(event){
            new Ajax.Request(this.href, {
                method:        "get",
                onSuccess:     function(transport){
                    var response = transport.responseText;
                    $$('#gtg_charities_locator_container #results_container')[0].update(response);
                }
            });
            event.stop();
        });
    });
}

function updateAutocompleterLinks(){
    $$('.menu-nav .form-search .search-autocomplete ul li a').each(function(item){
        item.observe('click', function(event){
            openLocatorWindow(this.href);
            event.stop();
        });
    });
}

function openLocatorWindow(url, options){
    
    var _options = {
        className:      "magento",
        resizable:      false,
        minimizable:    false,
        maximizable:    false,
        draggable:      false,
        recenterAuto:	false,
        destroyOnClose: true
    //maxWidth:       750,
    //maxHeight:      height
    };
    var _win = new Window('charities_locator', _options);
    document.charities_locator = _win;
    var _ajaxoptions = {
        method: "get",
        onComplete: function(){
            $('charities_locator_content').setStyle({
                overflowY: 'scroll'
            });
        }
    };
    var height=700;
    if(document.viewport.getHeight()<800){
        height=document.viewport.getHeight()-40;
    }
    document.charities_locator.setSize(770, height);
    document.charities_locator.setZIndex(10000);
    document.charities_locator.showCenter(true);
    document.charities_locator.setHTMLContent('<div style="position: relative; display: table; width: 100%; height: 100%; line-height: 100%; text-align: center;"><div style="position: relative; display: table-cell; vertical-align: middle;"><img src="/skin/frontend/enterprise/giftsthatgive/images/ajax-loader.gif"/></div></div>');
    document.charities_locator.setAjaxContent(url, _ajaxoptions, false, false);

    return false;
}

document.observe("dom:loaded", function() {
    $$('a[rel=#charities_locator]', 'form[rel=#charities_locator]','button[rel=#charities_locator]','a.charities_locator_opener').each(function(item){
        var _url = false;
        if(item.href){
            _url = item.href;// '/charitylocator/search/';
            item.observe('click', function(event){
                openLocatorWindow(_url);
                event.stop();
            });
        }
    /*if(item.action){
            $$('#search_mini_form #type_search')[0].observe('change', function(event){
                _url = item.action;

                if(this.value == "1")
                    Event.stopObserving($('search_mini_form'));
                else{
                    item.observe('submit', function(event){
                        openLocatorWindow(_url+"?"+item.serialize());
                        event.stop();
                    });
                }
            });
        }*/

    });
});

Window.prototype.show=function(modal){
    this.visible = true;
    if (modal) {
        // Hack for Safari !!
        if (typeof this.overlayOpacity == "undefined") {
            var that = this;
            setTimeout(function() {
                that.show(modal)
            }, 10);
            return;
        }
        Windows.addModalWindow(this);

        this.modal = true;
        this.setZIndex(Windows.maxZIndex + 1);
        Windows.unsetOverflow(this);
    }
    else
    if (!this.element.style.zIndex)
        this.setZIndex(Windows.maxZIndex + 1);

    // To restore overflow if need be
    if (this.oldStyle)
        this.getContent().setStyle({
            overflow: this.oldStyle
        });

    this.computeBounds();

    this._notify("onBeforeShow");
    if (this.options.showEffect != Element.show && this.options.showEffectOptions)
        this.options.showEffect(this.element, this.options.showEffectOptions);
    else
        this.options.showEffect(this.element);

    this._checkIEOverlapping();
    WindowUtilities.focusedWindow = this
    this._notify("onShow");
    try{
        $(this.element.id + '_focus_anchor').focus();
    }catch(e){
      
    }
}

Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;

Prototype.BrowserFeatures.Version = (navigator.userAgent.match( /.+(?:rv|it|Firefox|MSIE)[\/: ]([\d.]+)/ ) || [])[1];

Window.prototype.setAjaxContent = function(url, options, showCentered, showModal) {
    this.showFunction = showCentered ? "showCenter" : "show";
    this.showModal = showModal || false;
  
    options = options || {};

    // Clear HTML (and even iframe)
    //this.setHTMLContent("");
 
    this.onComplete = options.onComplete;
    if (! this._onCompleteHandler)
      this._onCompleteHandler = this._setAjaxContent.bind(this);
    options.onComplete = this._onCompleteHandler;

    new Ajax.Request(url, options);    
    options.onComplete = this.onComplete;
};

Window.prototype._getWindowBorderSize = function(event) {
    // Hack to get real window border size!!
    var div = this._createHiddenDiv(this.options.className + "_n")
    this.heightN = Element.getDimensions(div).height;    
    div.parentNode.removeChild(div)

    var div = this._createHiddenDiv(this.options.className + "_s")
    this.heightS = Element.getDimensions(div).height;    
    div.parentNode.removeChild(div)

    var div = this._createHiddenDiv(this.options.className + "_e")
    this.widthE = Element.getDimensions(div).width;    
    div.parentNode.removeChild(div)

    var div = this._createHiddenDiv(this.options.className + "_w")
    this.widthW = Element.getDimensions(div).width;
    div.parentNode.removeChild(div);
    
    var div = document.createElement("div");
    div.className = "overlay_" + this.options.className ;
    document.body.appendChild(div);
    //alert("no timeout:\nopacity: " + div.getStyle("opacity") + "\nwidth: " + document.defaultView.getComputedStyle(div, null).width);
    var that = this;
    
    // Workaround for Safari!!
    setTimeout(function() {that.overlayOpacity = ($(div).getStyle("opacity")); div.parentNode.removeChild(div);}, 10);
    
    // Workaround for IE!!
    if (Prototype.Browser.IE && Prototype.BrowserFeatures.Version < 7) {
      this.heightS = $(this.getId() +"_row3").getDimensions().height;
      this.heightN = $(this.getId() +"_row1").getDimensions().height;
    }

    // Safari size fix
    if (Prototype.Browser.WebKit && Prototype.Browser.WebKitVersion < 420)
      this.setSize(this.width, this.height);
    if (this.doMaximize)
      this.maximize();
    if (this.doMinimize)
      this.minimize();
  };

function switchForms(){
    $('charity_locator_advancedsearch_form_container').hide();
    $('charity_locator_simplesearch_form_container').show();
    return false;
};

$$('img').each(function(item){
   item.observe('error', function(){
       alert(this.src);
   });
});
