var IKEA = {};

/* Overlayer */
IKEA.overlayer = (function() {

    var _oldIE = ($.browser.msie && !(Object.prototype.toString.call(self.JSON) === "[object JSON]"));
    var _html = $('html');

    return {
        open            : function(layerid) {
               var layer = $(layerid);
               var layergroup = layer.parent().parent();
               if (_oldIE)  layergroup = layergroup.parent();

               if (layergroup.parent().get(0).tagName !== 'BODY') {

                    if ($('#innermost_layerwrapper').length === 0) {
                        $('body').append($(layergroup));
                        var layersgroup_wrapper = $('div', layergroup).get(0);
                        if (_oldIE)  layersgroup_wrapper = $('div', layersgroup_wrapper).get(0);
                        $(layersgroup_wrapper).attr('id',  'innermost_layerwrapper');
                     }
                     else {
                        layer.appendTo($('#innermost_layerwrapper'));
                        layergroup.remove();
                    }
              };

            _html.addClass('overlayer');
            $(layerid).toggleClass('openedlayer');

            return false;
        },

        close           : function(layerid) {
            _html.removeClass('overlayer');
            $(layerid).toggleClass('openedlayer');
            return false;
        }
    }
})();


IKEA.accordion = function(id) {

    this.id = null;
    this.opened = 0;
    this.speed = 320;
    this.collapsable = false;
    this.multiopened = false;

    this.acc = {
        'links' : undefined,
        'panels' : undefined
    };

    var _setLinkClass = function(element, _s) {
        var  panelid = element.attr('href');
        /* tab aperto e collassabile */
        if (element.hasClass('current')) {
            if (_s.collapsable ||  (!_s.collapsable && $('a.current', _s.id).length > 1)) {
                 element.removeClass('current');
                $(panelid).slideUp(_s.speed);
            }
        }
        else {
            /* il tab cliccato è chiuso */
            if (!_s.multiopened && $('a.current', _s.id).length > 0) {
                /* se non è consentita la multiapertura ed esiste un tab aperto*/
                    $($('a.current', _s.id).attr('href')).slideUp(_s.speed);
                    (_s['acc']['links']).removeClass('current');
            };

            /* apro l'elemento cliccato */
            element.addClass('current');
            $(panelid).slideDown(_s.speed);
        }
    };

    this.init  = function(options) {

        this.id = id;
        this.speed = options['speed'] || 300;
        this.opened = options['opened'] || -1;
        this.collapsable = options['collapsable'] || false;
        this.multiopened = options['multiopened'] || false;

        var _self = this;

        this['acc']['links'] = $('a.accordionlink',  _self.id);
        this['acc']['panels'] = $('.accordionpanel',  _self.id);


        this['acc']['panels'].hide();
        /* default tab link selected */
        if (this.opened > -1) {
            this['acc']['links'].each(function(i) { $(this).toggleClass('current',  i === _self.opened - 1); });
            $(this['acc']['panels'].get(this.opened-1)).show();
        };

        (this['acc']['links']).bind('click', function() {
            _setLinkClass($(this), _self);
            return false;
        });
    };

};



IKEA.getXHR = function () {

    var XHR = null;

    if(window.XMLHttpRequest) {
        XHR = new XMLHttpRequest();
    }
    else if(window.ActiveXObject) {
          try {
               XHR = new ActiveXObject('Msxml2.XMLHTTP');
          } catch(e) {
                try {
                    XHR = new ActiveXObject('Microsoft.XMLHTTP');
                } catch(e) {}
          }
    }

    return XHR;
};



IKEA.sleepingList = function(o) {

    var _session    = null;
    var _list       = {};
    var _xhr        = null;

    var _cookie     = {
        'name'      : 'ikea-session-sl',
        'life'      : 30
    };


    var isValidList     = function(list) {
        return (typeof $.json.deserialize(list) === 'object')
    };


    var ajaxCall = function(link, pars, callback) {

        var dt = new Date(), callStart = dt.getTime(), wait = 8, checkwait;

        _xhr.open("POST", link, true);
        _xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        _xhr.setRequestHeader("Content-length", pars.length);
        _xhr.setRequestHeader("X_REQUESTED_WITH", "XMLHttpRequest");
        _xhr.setRequestHeader("connection", "close");

        _xhr.onreadystatechange = function() {

            if(_xhr.readyState == 4) {
                checkwait = function(){};
                if(_xhr.status == 200 || _xhr.status == 304) {
                    callback(_xhr.responseText || _xhr.responseXML);
                };
            }
            else if(wait < 1000) {

                wait = wait * 1000;
                checkwait = function() {
                    dt = new Date();
                    if((dt.getTime() - callStart) > wait) {
                        _xhr.onreadystatechange = function(){return;};
                        _xhr.abort();
                    }
                    else setTimeout(checkwait, 100);
                };
                checkwait();
            };
        };

        _xhr.send(pars + "&rand=" + (new Date()).getTime());
    };


    var callToActionscript = function(id, value) {
       $(id).get(0).sendToActionScript(value);
    }



    return {

        'init'          : function() {
            if ($.cookie(_cookie.name) && ($.cookie($.cookie(_cookie.name)))) {
                _session    = $.cookie(_cookie.name);
                _list       = $.cookie($.cookie(_cookie.name));
                //IKEA.log('sessione da cookie : ' + _session);
                //IKEA.log('lista [' +  _session + '] : ' + _list);
            }
             else {
                _session = o.id;
                $.cookie(_cookie.name, _session, { path  : '/', expires: _cookie.life });
                $.cookie(_session, '{}', { path  : '/', expires: _cookie.life });
                //IKEA.log('sessione da server : ' + _session);
            };

            _xhr = IKEA.getXHR();
        },

/* ------------------------------------- */


        'addGlossaryItem'       : function(id, el) {
            var list = $.cookie(_session);

            if (isValidList(list) && !!(_xhr)) {
                //IKEA.log('la lista conteneva : ' + list);
                list = $.json.deserialize(list);
                //console.log("sid=" + _session +"&gid=" + id);
                ajaxCall("/mysleepinglist/insert/", "sid=" + _session +"&gid=" + id, function() {
                    //alert('ajax');
                    /* array di id */
                    if (typeof id === 'object') {
                        var a = id.length;
                        while (a--) {
                            //console.log(id[a]);
                            if (!list[id[a]]) list[id[a]] = 'add';
                        };
                    }
                    /* unico id */
                    else {
                        if (!list[id]) list[id] = 'add';
                    }
                    list = $.json.serialize(list);
                    //IKEA.log('la lista contiene : ' + list);
                    $.cookie(_session, list, { path  : '/', expires: _cookie.life });

										//alert(el);

                    if (el !== '') {
                        el.className = 'saved';
                        el.innerHTML = el.rel;
												jQuery(el).attr('title',el.rel);
                        el.onclick = function() {
                            return false;
                        }
                    }

                });
            };

            return false;
        },

        'removeGlossaryItem' : function(id, el) {
            var list = $.cookie(_session);
            var tmplist = {};

            if (isValidList(list) && !!(_xhr)) {
                //IKEA.log('la lista conteneva : ' + list);
                list = $.json.deserialize(list);

                ajaxCall("/mysleepinglist/delete/", "sid=" + _session +"&gid=" + id, function() {
                    if (list[id]) list[id] = 'del';
                    for (key in list) {
                        if (list[key] === 'add') tmplist[key] = 'add';
                    };
                    list = $.json.serialize(tmplist);
                    //IKEA.log('la lista contiene : ' + list);
                    $.cookie(_session, list, { path : '/', expires: _cookie.life });

                    if (el !== '') {
                        jQuery(el).parent().parent('.innercontblock').next().remove();
                        jQuery(el).parent().parent('.innercontblock').slideToggle('normal',function(){
                            jQuery(this).remove();
                            //console.log(jQuery('.innercontblock').length);
                            if(jQuery('.innercontblock').length == 0){
                                jQuery('#noresults').parent().prepend('<div class="top cl"></div>');
                                jQuery('#noresults').addClass('innercontblock').fadeIn();
                                jQuery('.stampapagina').fadeOut('normal',function(){jQuery(this).remove();});
                                jQuery('.inviapagina').fadeOut('normal',function(){jQuery(this).remove();});
                            }
                        });
                    }
                });
            };
            return false;
        },

        'openGlossaryItem'          : function(id) {
             ajaxCall("/glossario/open/", "gid=" + id, function(response) {
                callToActionscript('#swfikea', response);
             });
             return false;
        },


        'printSL'                   : function(id) {
             ajaxCall("/mysleepinglist/print/", "gid=" + id, function() { });
             return false;
        },


        'sendToAFriend'             : function(fields, error) {
             var pars = [], i = 0;
             for (f in fields) {
                pars[i] = [f, fields[f]].join('=');
                //if (f == 'slname' || f == 'mailtext') pars[i] = encodeURIComponent(pars[i]);
                ++i;
             };
             //console.log(pars.join('&'));
             ajaxCall("/inviapagina/sleepinglist/", pars.join('&')+'&rand='+ (new Date()).getTime(), function(response) {
                response = eval("("+response+")");
                $('#captchaid').attr('value', response[0]);
                if (response[1] == '0') {
                    if (error) $('#captchainput').parent().addClass('wrong');
                } else {
                    $('#captchainput').parent().removeClass('wrong');
                    IKEA.overlayer.close('#layerqty_send2friend');
                    IKEA.overlayer.open('#layerqty_sendok');
                }

                $('#captchaimg').attr('src', '/captcha/' + response[0] + '.png');

            });
            return false;
        }


    }
};







IKEA.log = function(log) {
    if('v'!='\v') {
        if(typeof console === 'object') console.log(log);
    }
    else {
        alert(log);
    }
}


jQuery(document).ready(function(){
	jQuery('.externallink').attr('target','_blank');
});
