﻿
/*	local javascript tools <http://www.citizenside.com>
*/

var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1 && navigator.userAgent.toLowerCase().indexOf('chrome') == -1;
var isIE = navigator.userAgent.toLowerCase().indexOf('msie') > -1;
var isIE9 = navigator.userAgent.toLowerCase().indexOf('msie 9') > -1;
var isIE8 = navigator.userAgent.toLowerCase().indexOf('msie 8') > -1;
var isIE7 = navigator.userAgent.toLowerCase().indexOf('msie 7') > -1;
var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') > -1;
var isWindows = navigator.userAgent.toLowerCase().indexOf('windows') > -1;
var isBot = navigator.userAgent.toLowerCase().indexOf('googlebot') > -1;

/* console for IE */
var alertFallback = true;
if (typeof console === "undefined" || typeof console.log === "undefined") {
    console = {};
    if (alertFallback) {
        console.log = function(msg) {
            //alert(msg);
        };
    } else {
        console.log = function() { };
    }
}


function getLanguageId() {
    return parseInt(readCookie('UserLanguage'));
}

function isIE7() {
    return document.all && !window.opera && window.XMLHttpRequest;
}

//////////////////// AUTH ////////////////////
var userSettings = '';
var loginIn = false;

jQuery(document).bind('authchange', function(evt, islogged, previousIdLanguage) {
    if (previousIdLanguage && previousIdLanguage != getLanguageId())
        window.location.reload(true);
});

function doLogin(loginElmId, defaultLoginTxt, passElmId, defaultPassnTxt, pnlElmId, format, urlBase, rememberElmId) {
    if (jQuery('#' + passElmId).prop('value') != defaultPassnTxt
         && jQuery('#' + passElmId).prop('value') != ''
         && jQuery('#' + loginElmId).prop('value') != defaultLoginTxt
         && jQuery('#' + loginElmId).prop('value') != ''
        ) {
        doLoginBase(jQuery('#' + loginElmId).prop('value'), jQuery('#' + passElmId).prop('value'), pnlElmId, urlBase, rememberElmId);
    }
    else {
        jQuery('#' + pnlElmId).addClass('loginError');
        jQuery('#' + loginElmId).focus();
    }
}
function doLoginBase(login, password, pnlElmId, urlBase, rememberElmId) {

    if (loginIn) return false;
    loginIn = true;

    var dataValue = 'login=' + login + '&pass=' + Base64.encode(password) + '&dologin=true';
    var remember = false;
    if (rememberElmId && jQuery('#' + rememberElmId).is(':checked')) {
        dataValue += "&rememberme=true";
        remember = true;
    }
    jQuery('#' + pnlElmId).removeClass('loginError');
    jQuery('#' + pnlElmId).addClass('loginLoading');

    var currentIdLanguage = getLanguageId();

    jQuery.ajax({
        url: urlBase + 'modules/authentication/api/authenticationapi.aspx',
        type: 'POST',
        data: dataValue,
        success: function(data) {
            loginIn = false;
            if (parseInt(data) <= 0) {
                jQuery('#' + pnlElmId).removeClass('loginLoading');
                jQuery('#' + pnlElmId).addClass('loginError');
            } else {
                userSettings = data;
                if (remember)
                    newExpiringCookie("UserRemindMe", data, 30);

                if (top == self)
                    jQuery(document).trigger('authchange', [true, currentIdLanguage, data]);
                else
                    parent.jQuery(parent.document).trigger('authchange', [true, currentIdLanguage, data]);

                //window.setTimeout(function() { jQuery('#' + pnlElmId).removeClass('loginLoading'); }, 1000);
            }
        },
        error: function() {
            loginIn = false;
            jQuery('#' + pnlElmId).removeClass('loginLoading');
            jQuery('#' + pnlElmId).addClass('loginError');
        }
    });
    return false;
}

function doLogout(pnlElmId, format, urlBase) {
    var dataValue = 'dologout=true';
    userSettings = '';
    jQuery('#' + pnlElmId).addClass('loginLoading');
    jQuery.ajax({
        url: urlBase + 'modules/authentication/api/authenticationapi.aspx',
        type: 'POST',
        data: dataValue,
        complete: function() {
            //jQuery('#' + pnlElmId).removeClass('loginLoading');
            //window.location.reload(true);
            jQuery(document).trigger('authchange', [false]);
        }
    });
    return false;
}

function isLogged(force, baseUrl) {
    if (force && baseUrl)
        jQuery.ajax({
            url: baseUrl + 'modules/authentication/api/authenticationapi.aspx',
            type: 'POST',
            success: function(data) {
                if (parseInt(data) <= 0) {
                    userSettings = '';
                } else {
                    userSettings = data;
                    jQuery(document).trigger('islogged');
                }
            },
            error: function() {
                userSettings = '';
            }
        });
    else {
        if (userSettings && userSettings.length > 0) {
            return true;
        } else {
            return false;
        }
    }
}

var _isCertified;
function isCertified(baseUrl, callback) {
    if (_isCertified == null) {
        jQuery(document).bind('authchange islogged iscertified', function() {
            console.log('calling isCertified');
            jQuery.ajax({
                url: baseUrl + 'modules/authentication/api/authenticationapi.aspx?iscertified=',
                type: 'POST',
                success: function(data) {
                    _isCertified = eval(data)
                    callback(_isCertified);
                }
            });
        });
        jQuery(document).trigger('iscertified');
    } else {
        callback(_isCertified);
    }
}

function isLoggedUser(username) {
    if (!isLogged())
        return false;
    if (getLoggedUsername() == username)
        return true;
    else
        return false;
}
function getLoggedUsername() {
    if (!isLogged())
        return '';

    var cookieValue = readCookie("UserName");
    if (cookieValue)
        return cookieValue;
    else
        return '';
}

//////////////////////////////////////////////

//////////////////// VOTE ////////////////////
var VoteObjectArray = new Array();

function VoteObject(containerElmId, nbVotesElmId, nbvotes, cookieId, url, voteType, votableId) {
    this.ContainerElmId = containerElmId;
    this.NbVotesElmId = nbVotesElmId;
    this.CookieId = cookieId;
    this.NbVotes = nbvotes;
    this.APIUrl = url;
    this.VoteType = voteType;
    this.VotableId = parseInt(votableId);
    this.Status = nbvotes == 0 ? 0 : 1;

    this.initVote = function() {
        if (this.VotableId <= 0)
            return this;

        var cookieExists = readCookie(this.CookieId);
        if (cookieExists && cookieExists == 'true') {
            this.Status = 2
        } else {
            this.initClick();
        }
        this.addToVoteManager();
        this.changeDisplay();
        //this.updateValue();
        return this;
    };

    this.modifyVote = function(cookieId, voteType, votableId) {
        this.VoteType = voteType;
        this.VotableId = parseInt(votableId);
        this.CookieId = cookieId;

        if (this.VotableId <= 0)
            return;

        var cookieExists = readCookie(this.CookieId);
        if (cookieExists && cookieExists == 'true') {
            this.Status = 2
            jQuery('#' + this.ContainerElmId).unbind('click');
        } else {
            this.Status = 1
            this.initClick();
        }
        this.updateValue();
        this.changeDisplay();
    };


    this.addToVoteManager = function() {
        VoteObjectArray.push(this);
    };

    this.changeDisplay = function() {
        jQuery('#' + this.ContainerElmId).removeClass('noVote');
        jQuery('#' + this.ContainerElmId).removeClass('voted');
        if (this.NbVotes == 0)
            jQuery('#' + this.NbVotesElmId).html('+');
        switch (this.Status) {
            case 0: //not voted but no vote
                jQuery('#' + this.ContainerElmId).addClass('novote');
                break;
            case 2: //voted
                jQuery('#' + this.ContainerElmId).addClass('voted');
                break;
        }
    };

    this.initClick = function() {
        var voteObj = this;
        jQuery('#' + this.ContainerElmId).unbind('click');
        jQuery('#' + this.ContainerElmId).bind('click', function() { voteObj.doVote(); });
    };

    this.doVote = function() {
        jQuery('#' + this.ContainerElmId).unbind('click');
        newExpiringCookie(this.CookieId, "true", 30);
        this.Status = 2;
        if (!isNaN(parseInt(jQuery('#' + this.NbVotesElmId).html())))
            this.NbVotes = parseInt(jQuery('#' + this.NbVotesElmId).html());
        this.NbVotes++;
        jQuery('#' + this.NbVotesElmId).html('' + this.NbVotes);
        this.changeDisplay();
        jQuery.ajax({
            url: this.APIUrl + "?id=" + this.VotableId + "&type=" + this.VoteType + "&action=vote"
        });
    };

    this.updateValue = function() {
        var voteObj = this;
        if (voteObj.VotableId <= 0)
            return;
        jQuery('#' + this.ContainerElmId).addClass('voteLoading');
        jQuery.ajax({
            url: voteObj.APIUrl + "?id=" + this.VotableId + "&type=" + this.VoteType,
            success: function(data) {
                var updatedNbVotes = parseInt(data);
                if (updatedNbVotes > 0) {
                    jQuery('#' + voteObj.NbVotesElmId).html(updatedNbVotes);
                }
                jQuery('#' + voteObj.ContainerElmId).removeClass('voteLoading');
            },
            error: function() {
                jQuery('#' + voteObj.ContainerElmId).removeClass('voteLoading');
            }
        });
    };

    this.toString = function() {
        return '[' + this.ContainerElmId + '|' + this.VoteType + '|' + this.VotableId + ']';
    };
}

jQuery(document).ready(function() {

    for (i = 0; i < VoteObjectArray.length; i++) {
        jQuery('#' + VoteObjectArray[i].ContainerElmId).addClass('voteLoading');
    };


    var firstVoteObject = VoteObjectArray[0];
    if (firstVoteObject) {
        jQuery.ajax({
            url: firstVoteObject.APIUrl + "?id=" + firstVoteObject.VotableId + "&type=" + firstVoteObject.VoteType,
            type: "POST",
            data: "array=" + VoteObjectArray.join(),
            success: function(data) {
                var jsonData = eval('(' + data + ')');
                var voteObject = VoteObjectArray.pop();
                while (voteObject) {
                    var entry = JSONQuery("$.VoteObjectArray[?elmId='" + voteObject.ContainerElmId + "']", jsonData);
                    if (entry) {
                        var updatedNbVotes = parseInt(entry[0].nbVotes);
                        if (updatedNbVotes > 0) {
                            jQuery('#' + voteObject.NbVotesElmId).html(updatedNbVotes);
                        }
                    }
                    jQuery('#' + voteObject.ContainerElmId).removeClass('voteLoading');
                    voteObject = VoteObjectArray.pop();
                }
            },
            error: function() {
                var voteObject = VoteObjectArray.pop();
                while (voteObject) {
                    jQuery('#' + voteObject.ContainerElmId).removeClass('voteLoading');
                    voteObject = VoteObjectArray.pop();
                }
            }
        });
    }
});
/////////////////////////////////////////

///////////////// POLL //////////////////

function PollObject(containerElmId, cookieId, urlAPI, urlRender, pollId, nbVotes, format, idvoteevent, idresultsevent) {
    this.ContainerElmId = containerElmId;
    this.CookieId = cookieId;
    this.NbVotes = nbVotes;
    this.APIUrl = urlAPI;
    this.RenderUrl = urlRender;
    this.PollId = pollId;
    this.Format = format;
    this.IDVoteEvent = idvoteevent;
    this.IDResultsEvent = idresultsevent;
    this.Status = 'notvoted'; //NbVotes == 0 ? '' : '';

    this.initPoll = function() {
        var cookieExists = readCookie(this.CookieId);
        if (cookieExists && cookieExists == 'true') {
            this.Status = 'voted';
        }
        this.updateDisplay(true);
        this.initEvent();
    };

    this.updateDisplay = function(atLoad) {
        var pollObj = this;
        //jQuery('#' + this.ContainerElmId).removeClass('pollLoading');
        jQuery('#' + this.ContainerElmId).removeClass('pollError');
        jQuery('#' + this.ContainerElmId).addClass('pollLoading');
        jQuery.ajax({
            url: pollObj.RenderUrl + "&status=" + pollObj.Status + "&format=" + pollObj.Format,
            success: function(data) {
                jQuery('#' + pollObj.ContainerElmId).removeClass('pollLoading');
                jQuery('#' + pollObj.ContainerElmId).html(data);
            },
            error: function() {
                jQuery('#' + pollObj.ContainerElmId).removeClass('pollLoading');
                jQuery('#' + pollObj.ContainerElmId).hide();
            }
        });
    };

    this.initEvent = function() {
        var pollObj = this;
        jQuery(document).unbind(pollObj.IDVoteEvent);
        jQuery(document).unbind(pollObj.IDResultsEvent);
        jQuery(document).bind(pollObj.IDVoteEvent, function(event, idAnswer) { pollObj.doVote(idAnswer); });
        jQuery(document).bind(pollObj.IDResultsEvent, function(event, showResults) { pollObj.doToggleResults(showResults); });
    };

    this.doVote = function(idAnswer) {
        var pollObj = this;
        jQuery(document).unbind(pollObj.IDVoteEvent);
        jQuery(document).unbind(pollObj.IDResultsEvent);
        newExpiringCookie(this.CookieId, "true", 30);
        this.Status = 'voted';
        this.NbVotes++;
        jQuery('#' + this.ContainerElmId).addClass('pollLoading');
        jQuery.ajax({
            url: pollObj.APIUrl + "&action=vote&answer=" + idAnswer,
            success: function(data) {
                pollObj.updateDisplay(false);
            },
            error: function(data) {
                jQuery('#' + pollObj.ContainerElmId).removeClass('pollLoading');
                jQuery('#' + pollObj.ContainerElmId).addClass('pollError');
            }
        });
    };

    this.doToggleResults = function(showResults) {
        if (showResults)
            this.Status = 'results';
        else
            this.Status = 'notvoted';
        this.updateDisplay(false);
        this.Status = 'notvoted';
    };

}

/////////////////////////////////////////

///////////////// ABUSE REPORT //////////////////

function AbuseReportObject(containerElmId, urlAPI, abuseType, abuseId) {
    this.ContainerElmId = containerElmId;
    this.APIUrl = urlAPI;
    this.AbuseType = abuseType;
    this.AbuseId = abuseId;

    this.initAbuseReport = function() {
        var arObj = this;
        jQuery('#' + arObj.ContainerElmId).bind('click', function() { arObj.doAbuseReport(); });
        return this;
    };

    this.modifyAbuseReport = function(abuseType, abuseId) {
        var arObj = this;
        this.AbuseType = abuseType;
        this.AbuseId = abuseId;
        jQuery('#' + arObj.ContainerElmId).addClass('notreported');
        jQuery('#' + arObj.ContainerElmId).removeClass('reported');
        jQuery('#' + arObj.ContainerElmId).unbind('click');
        jQuery('#' + arObj.ContainerElmId).bind('click', function() { arObj.doAbuseReport(); });
    };

    this.doAbuseReport = function() {
        var arObj = this;
        jQuery('#' + arObj.ContainerElmId).unbind('click');
        jQuery.ajax({
            url: arObj.APIUrl + "?id=" + this.AbuseId + "&type=" + this.AbuseType + "&action=report"
        });
        jQuery('#' + arObj.ContainerElmId).removeClass('notreported');
        jQuery('#' + arObj.ContainerElmId).addClass('reported');
    };
}

/////////////////////////////////////////

//////////////// CART ///////////////////

var CartObjectArray = new Array();

function CartObject(containerElmId, cookieId, url, buyableId, buyableType, publicationSize, action, isLB, isHistory, needConfirm, enableStatus, circulation) {
    this.ContainerElmId = containerElmId;
    this.CookieId = cookieId;
    this.APIUrl = url;
    this.IsLB = isLB;
    this.BuyableId = buyableId;
    this.BuyableType = buyableType;
    this.Action = action;
    this.PublicationSize = publicationSize;
    this.Circulation = circulation;
    this.Status = 0;
    this.IsHistory = isHistory;
    this.Confirm = needConfirm;
    this.EnableStatus = enableStatus;

    this.initCart = function(doNotRebind) {

        var cookieExists = readCookie(this.CookieId);
        if (!this.IsHistory && this.Action != 9 && cookieExists && cookieExists.contains('[' + this.BuyableId + '|' + this.BuyableType + '|'))
            this.Status = 2;
        else
            this.Status = 0;
        this.initClick();
        this.changeDisplay();

        var cartObj = this;
        if (!doNotRebind) {
            if (cartObj.IsLB) {
                jQuery(document).bind('lightboxupdated', function(event, buyableId, buyableType, publicationSize, circulation) {
                    cartObj.initCart(true);
                });
            }
            else {
                jQuery(document).bind('cartupdated', function(event, buyableId, buyableType, publicationSize, circulation) {
                    cartObj.initCart(true);

                });
            }
        }
    };

    this.modifyBuyable = function(buyableId) {
        this.BuyableId = buyableId;
        this.initCart(true);
    };

    this.modifySize = function(size, circulation) {
        this.PublicationSize = size;
        this.Circulation = circulation;
        this.doCart();
    };

    this.addToCartManager = function() {
        CartObjectArray.push(this);
    };

    this.changeDisplay = function() {
        switch (this.Status) {
            case -1: //error
                this.setStatusClass('cartError');
                break;
            case 0: //not in cart
                this.setStatusClass('notAdded');
                break;
            case 1: //deleted
                this.setStatusClass('deleted');
                break;
            case 2: //already in cart
                this.setStatusClass('inCart');
                break;
        }
    };

    this.setStatusClass = function(className, callbackMethod) {
        var cartObj = this;
        jQuery('#' + this.ContainerElmId).fadeOut(100, function() {
            jQuery('#' + cartObj.ContainerElmId).removeClass('confirm');
            jQuery('#' + cartObj.ContainerElmId).removeClass('deleted');
            jQuery('#' + cartObj.ContainerElmId).removeClass('notAdded');
            jQuery('#' + cartObj.ContainerElmId).removeClass('added');
            jQuery('#' + cartObj.ContainerElmId).removeClass('inCart');
            jQuery('#' + cartObj.ContainerElmId).removeClass('cartError');
            jQuery('#' + cartObj.ContainerElmId).removeClass('cartLoading');
            if (className && className.length > 0)
                jQuery('#' + cartObj.ContainerElmId).addClass(className);
            jQuery('#' + cartObj.ContainerElmId).fadeIn(100, callbackMethod);
        });
    };

    this.initClick = function() {

        var cartObj = this;
        jQuery('#' + this.ContainerElmId).unbind('click');

        if (this.Action == 8)//drop
            jQuery('#' + this.ContainerElmId).bind('dropbuyable', function() { cartObj.doCart(); });
        else if (this.Action == 11)//promo
            jQuery('#' + this.ContainerElmId).bind('click', function() { cartObj.doPromo(); });
        else if (this.Action == 4)//validate
            jQuery('#' + this.ContainerElmId).bind('click', function() { cartObj.doValidate(); });
        else {
            if (this.Confirm)
                jQuery('#' + this.ContainerElmId).bind('click', function() { cartObj.doCartConfirm(); });
            else if (!this.EnableStatus || this.Status != 2)
                jQuery('#' + this.ContainerElmId).bind('click', function() { cartObj.doCart(); });

        }
    };

    this.doValidate = function() {
        var cartObj = this;
        jQuery('#cd_cguContainer').removeClass('error');
        if (!jQuery('#cd_cgu').prop('checked')) {
            jQuery('#cd_cguContainer').addClass('error');
        } else {
            cartObj.doCart();
        }
    };

    this.doCartConfirm = function() {
        var cartObj = this;
        var timer = window.setTimeout(function() {
            jQuery('#' + cartObj.ContainerElmId).unbind('click');
            jQuery('#' + cartObj.ContainerElmId).bind('click', function() { cartObj.doCartConfirm(); });
            cartObj.changeDisplay();
        }, 5000);
        jQuery('#' + this.ContainerElmId).unbind('click');
        jQuery('#' + this.ContainerElmId).bind('click', function() { clearTimeout(timer); cartObj.doCart(); });
        this.setStatusClass('confirm');
    };

    this.doPromo = function() {
        var cartObj = this;
        if (jQuery('#' + jQuery('#' + cartObj.ContainerElmId).attr('for')).val().length > 0) {
            cartObj.setStatusClass('cartLoading');
            jQuery('#' + cartObj.ContainerElmId).unbind('click');
            jQuery('#' + cartObj.ContainerElmId).unbind('dropbuyable');

            jQuery.ajax({
                url: this.APIUrl + "&promo=" + jQuery('#' + jQuery('#' + cartObj.ContainerElmId).attr('for')).val(),
                success: function(data) {
                    cartObj.cartAjaxSuccess(data, cartObj);
                    jQuery('#' + jQuery('#' + cartObj.ContainerElmId).attr('for')).val('');
                },
                error: function(data) {
                    cartObj.setStatusClass('cartError');
                }
            });
        }
    };

    this.doCart = function() {
        var cartObj = this;
        cartObj.setStatusClass('cartLoading');
        jQuery('#' + cartObj.ContainerElmId).unbind('click');
        jQuery('#' + cartObj.ContainerElmId).unbind('dropbuyable');

        var cookieExists = readCookie(this.CookieId);
        if (cookieExists && !cookieExists.contains('[' + cartObj.BuyableId + '|' + cartObj.BuyableType + '|' + cartObj.PublicationSize + '|' + cartObj.Circulation + ']'))
            newSessionCookie(this.CookieId, cookieExists + '[' + cartObj.BuyableId + '|' + cartObj.BuyableType + '|' + cartObj.PublicationSize + '|' + cartObj.Circulation + ']');
        else {
            newSessionCookie(this.CookieId, '[' + cartObj.BuyableId + '|' + cartObj.BuyableType + '|' + cartObj.PublicationSize + '|' + cartObj.Circulation + ']');
        }
        jQuery.ajax({
            url: this.APIUrl + "&id=" + this.BuyableId + "&size=" + this.PublicationSize + "&circulation=" + this.Circulation,
            success: function(data) {
                cartObj.cartAjaxSuccess(data, cartObj);
            },
            error: function(data) {
                cartObj.setStatusClass('cartError');
            }
        });
    };

    this.cartAjaxSuccess = function(data, cartObj) {
        var jsonData = eval('(' + data + ')');

        var statusChange = JSONQuery("$.CartResponse[?Action='status']", jsonData);
        if (statusChange && statusChange.length > 0) {
            var done = false;
            if (!isNaN(parseInt(statusChange[0].Status))) {
                cartObj.Status = parseInt(statusChange[0].Status);
                cartObj.changeDisplay();
                if (!this.EnableStatus)
                    cartObj.initClick();

                var eventName = 'cartchanged';
                if (cartObj.IsLB)
                    eventName = 'lightboxchanged';

                if (top == self)
                    jQuery(document).trigger(eventName, [cartObj.BuyableId, cartObj.BuyableType, action, cartObj.PublicationSize, cartObj.Circulation]);
                else
                    parent.jQuery(parent.document).trigger(eventName, [cartObj.BuyableId, cartObj.BuyableType, action, cartObj.PublicationSize, cartObj.Circulation]);

            } else {
                cartObj.setStatusClass('cartError');
            }
            done = true;
        }

        var alertPopup = JSONQuery("$.CartResponse[?Action='alert']", jsonData);
        if (alertPopup && alertPopup.length > 0) {
            alert(alertPopup[0].Message);
            if (!this.EnableStatus)
                cartObj.initClick();
            done = true;
        }


        var fairuse = JSONQuery("$.CartResponse[?Action='fairuse']", jsonData);
        if (fairuse && fairuse.length > 0) {
            jQuery(document).trigger('fairusevalidated');
            window.setTimeout(function() { document.location = fairuse[0].Url; }, 1000);
            done = true;
        }

        var redirect = JSONQuery("$.CartResponse[?Action='redirect']", jsonData);
        if (redirect && redirect.length > 0) {
            if (!this.EnableStatus) {
                cartObj.initClick();
                cartObj.setStatusClass('notAdded', function() {
                    window.setTimeout(function() { document.location = redirect[0].Url; }, 500);
                });
            } else {
                document.location = redirect[0].Url;
            }
            done = true;
        }

        var confirmPopup = JSONQuery("$.CartResponse[?Action='confirm']", jsonData);
        if (confirmPopup && confirmPopup.length > 0) {
            if (confirm(confirmPopup[0].Message))
                document.location = confirmPopup[0].Url;
            else
                cartObj.initClick();
            done = true;
        }

        var trigg = JSONQuery("$.CartResponse[?Action='trigger']", jsonData);
        if (trigg && trigg.length > 0) {
            if (top == self)
                jQuery(document).trigger(trigg[0].Event, [cartObj.BuyableId, cartObj.BuyableType, action, cartObj.PublicationSize, cartObj.Circulation]);
            else
                parent.jQuery(parent.document).trigger(trigg[0].Event, [cartObj.BuyableId, cartObj.BuyableType, action, cartObj.PublicationSize, cartObj.Circulation]);

            cartObj.initClick();
            done = true;
        }

        if (!done)
            cartObj.setStatusClass('cartError');
    };

    this.updateValue = function() {
        var cartObj = this;
        cartObj.setStatusClass('cartLoading');
        jQuery.ajax({
            url: cartObj.APIUrl,
            success: function(data) {
                cartObj.setStatusClass('');
                var cartStatus = parseInt(data);
                if (cartStatus >= 0) {
                    cartObj.Status = cartStatus;
                    cartObj.updateValue();
                }
            },
            error: function() {
                cartObj.setStatusClass('cartError');
            }
        });
    };

}
jQuery(document).ready(function() {
    if (typeof jQuery('.draggable-buyable').draggable == 'function' && !(jQuery.browser.msie && jQuery.browser.version <= 7))
        jQuery('.draggable-buyable').draggable({
            containment: 'document',
            opacity: 1,
            revert: 'invalid',
            helper: 'clone',
            //zindex: '11000',
            scroll: false,
            stack: "#cs",
            start: function(event, ui) {
                ui.helper.siblings('.draggable-buyable').addClass('ui-draggable-original');
            },
            stop: function(event, ui) {
                ui.helper.siblings('.draggable-buyable').removeClass('ui-draggable-original');
            }

        });
});
function dragAddCart(isLb, ui) {
    if (isLb)
        jQuery(ui.draggable).parent().parent().children('.draggable-buyable-handler-lb').trigger('dropbuyable');
    else
        jQuery(ui.draggable).parent().parent().children('.draggable-buyable-handler').trigger('dropbuyable')
}

/////////////////////////////////////////

//////////////// COMMONS ////////////////

var isMSIE = !jQuery.support.cssFloat;

function confirmFairUse(element) {
    if (element && !element.checked) {
        jQuery(document).trigger('fairusedisabled', [element]);
    }
}

var defaultAjaxManager = jQuery.manageAjax.create('defaultDynamicLoading', { queue: true });

function updateBlockObject(url) {
    this.APIUrl = url;
    this.arrayElmId = new Array();
    this.arrayFormat = new Array();
    this.arrayElmIdQueued = new Array();
    this.arrayFormatQueued = new Array();

    this.addBlock = function(elmId, format, queued) {
        if (queued) {
            this.arrayElmIdQueued.push(elmId);
            this.arrayFormatQueued.push(format);
        } else {
            this.arrayElmId.push(elmId);
            this.arrayFormat.push(format);
        }
    };

    this.update = function(animationType) {
        if (this.arrayElmId.length > 0) {
            var myObj = this;
            updateBlock(this.arrayElmId.join('|'), this.APIUrl + '&format=' + this.arrayFormat.join('|'), animationType, function() {
                if (myObj.arrayElmIdQueued.length > 0)
                    window.setTimeout(function() { updateBlock(myObj.arrayElmIdQueued.join('|'), myObj.APIUrl + '&format=' + myObj.arrayFormatQueued.join('|'), animationType); }, 5000);
            });
        }
    };
}

function updateBlock(elmIdsStr, urlFrame, animationType, callbackMethod, callbackMethodArgument, append, ajaxManager, isFrame, handler) {
    var callTheCallBack = function() {
        var elmIdsUnClass = elmIdsStr.split('|');
        for (i = 0; i < elmIdsUnClass.length; i++) {
            jQuery('#' + elmIdsUnClass[i]).removeClass('blockLoading');
        }
        if (callbackMethod) {
            if (callbackMethodArgument)
                callbackMethod(callbackMethodArgument);
            else
                callbackMethod();
        }
    };

    if (isFrame) {
        var heightOffset = jQuery(handler || "#" + elmIdsStr).attr("heightOffset") || 0;
        var frameAutoHeight = jQuery(handler || "#" + elmIdsStr).attr("frameAutoHeight") || "true";
        var frameHeight = jQuery(handler || "#" + elmIdsStr).attr("frameHeight") || 400;
        var frameWidth = jQuery(handler || "#" + elmIdsStr).attr("frameWidth") || 100;
        var frameScroll = jQuery(handler || "#" + elmIdsStr).attr("frameScroll") || "no";
        var properties = 'class="frame ' + (frameHeight ? '' : 'autoHeight') + '" scrolling="' + frameScroll + '" width="' + frameWidth + '" ' + (frameHeight ? 'height="' + frameHeight + '"' : '');


        jQuery('#' + elmIdsStr).html('<IFRAME id="' + elmIdsStr + '_frame" ' + properties + ' src="' + urlFrame + '" frameborder=no >');

        jQuery('#' + elmIdsStr).addClass('blockLoading');



        if (frameAutoHeight == "true")
            jQuery('#' + elmIdsStr + '_frame').iframeAutoHeight({
                heightOffset: heightOffset,
                callback: callTheCallBack
            });
        else
            jQuery('#' + elmIdsStr + '_frame').load(callTheCallBack);
    } else {

        var elmIdsClass = elmIdsStr.split('|');
        for (i = 0; i < elmIdsClass.length; i++) {
            jQuery('#' + elmIdsClass[i]).addClass('blockLoading');
        }

        if (!ajaxManager)
            ajaxManager = defaultAjaxManager;
        ajaxManager.add({
            url: urlFrame,
            error: function() {
                callTheCallBack();
            },
            success: function(dataStr) {
                var elmIds = elmIdsStr.split('|');
                var datas;
                if (elmIds.length > 1)
                    datas = dataStr.split('|');
                else
                    datas = new Array(dataStr);

                for (i = 0; i < elmIds.length; i++) {
                    jQuery('#' + elmIds).removeClass('blockLoading');

                    var data = datas[i];
                    var elmId = elmIds[i];
                    if (data && data.length > 0) {
                        if (append) {
                            jQuery('#' + elmId).append(data);
                        }
                        else {

                            switch (animationType) {
                                case 'none':
                                    try { jQuery('#' + elmId).html(data); callTheCallBack(); } catch (E) { console.log(E); }
                                    break;
                                case 'slideDown':
                                    jQuery('#' + elmId).hide();
                                    try { jQuery('#' + elmId).html(data); } catch (E) { console.log(E); }
                                    jQuery('#' + elmId).slideDown(1500, callTheCallBack);
                                    break;
                                default:
                                case 'fadeIn':
                                    jQuery('#' + elmId).hide();
                                    try { jQuery('#' + elmId).html(data); } catch (E) { console.log(E); }
                                    jQuery('#' + elmId).fadeIn(1000, callTheCallBack);
                                    break;
                            }
                        }
                    } else {
                        if (!append)
                            switch (animationType) {
                            case 'none':
                                jQuery('#' + elmIds[i]).html('');
                                jQuery('#' + elmIds[i]).show();
                                break;
                            case 'slideDown':
                                jQuery('#' + elmIds[i]).slideUp(1500, function() { jQuery('#' + elmIds[i]).html(''); jQuery('#' + elmIds[i]).show(); callTheCallBack(); });
                                break;
                            default:
                            case 'fadeIn':
                                jQuery('#' + elmIds[i]).fadeOut(1000, function() { jQuery('#' + elmIds[i]).html(''); jQuery('#' + elmIds[i]).show(); callTheCallBack(); });
                                break;
                        }
                    }
                }
            }
        });
    }
}


function fireOnchange(elementId) {
    try {
        jQuery("#" + elementId).change();
    } catch (E) { }
}

function randomFromTo(from, to) {
    return Math.floor(Math.random() * (to - from + 1) + from);
}

function getQueryValue(key) {
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + key + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null) {
        if (jQuery('#_hdn' + key).length > 0)
            return jQuery('#_hdn' + key).val();
        else
            return "";
    }
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

String.prototype.startsWith = function(str)
{ return (this.match("^" + str) == str) }

String.prototype.endsWith = function(str)
{ return (this.match(str + "$") == str) }

String.prototype.contains = function(str)
{ return (this.indexOf(str) >= 0) }

String.prototype.trim = function()
{ return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "")) }

if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

function getRequestQueryString(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}


function clearRadioButton(rblTable) {
    if (rblTable) {
        for (var count = 0; count < rblTable.rows.length; count++) {
            if (rblTable.rows[count].cells[0].getElementsByTagName('input').length > 0) {
                var rbn = rblTable.rows[count].cells[0].getElementsByTagName('input')[0];
                if (rbn != null) {
                    if (rbn.checked == true) {
                        rbn.checked = false;

                    }
                }
            }
        }
    }
}

function isKeyPressReturn(e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        return true;
    }
    return false;
}


function printDateTime(date) {
    return printDate(date) + " " + printTime(date);
}

function printDate(date) {
    var d = date.getDate();
    var day = (d < 10) ? '0' + d : d;
    var m = date.getMonth() + 1;
    var month = (m < 10) ? '0' + m : m;
    var yy = date.getYear();
    var year = (yy < 1000) ? yy + 1900 : yy;

    switch (getLanguageId()) {
        default:
        case 1: //FR
            return day + '/' + month + '/' + year;
        case 2: //EN
            return month + '/' + day + '/' + year;
    }
}

function printTime(date) {
    var h = date.getHours();
    var hours = (h < 10) ? '0' + h : h;
    var m = date.getMinutes();
    var minutes = (m < 10) ? '0' + m : m;
    var s = date.getSeconds();
    var seconds = (s < 10) ? '0' + s : s;

    switch (getLanguageId()) {
        default:
        case 1: //FR
            return hours + ':' + minutes + ':' + seconds;
        case 2: //EN
            return (hours > 12 ? hours - 12 : hours) + ':' + minutes + ':' + seconds + ' ' + (hours > 12 ? 'PM' : 'AM');
    }
}



/////////////////////// DDL /////////////////////

var timeout = 500;
var opentimeout = 200;
var closetimer = 0;
var opentimer = 0;
var panelId = null;
var panelActivatorId = null;
var panelActivatorIdOriginalCssClass = null;

function jsddm_open(listId, activatorId, originalCssClass, callbackmethod) {
    jsddm_canceltimer();
    if (panelId && panelId != listId)
        jsddm_close(panelId, panelActivatorId, panelActivatorIdOriginalCssClass);
    panelId = listId;
    panelActivatorId = activatorId;
    panelActivatorIdOriginalCssClass = originalCssClass;
    jQuery('#' + listId).slideDown('fast', function() {
        if (callbackmethod)
            callbackmethod();
    });
    if (activatorId && originalCssClass)
        jQuery('#' + activatorId).attr('class', originalCssClass + '_hover');
}

function jsddm_close(listId, activatorId, originalCssClass, callbackmethod) {
    jsddm_cancelopentimer();
    if (activatorId && originalCssClass)
        jQuery('#' + activatorId).attr('class', originalCssClass);
    jQuery('#' + listId).slideUp('fast', function() {
        if (callbackmethod)
            callbackmethod();
    });
    panelId = null;
    panelActivatorId = null;
    panelActivatorIdOriginalCssClass = null;
}

function jsddm_timer(listId, activatorId, originalCssClass, callbackmethod) {
    jsddm_cancelopentimer();
    closetimer = window.setTimeout(function() {
        jsddm_close(listId, activatorId, originalCssClass, callbackmethod);
    }, timeout);
}

function jsddm_canceltimer() {
    if (closetimer) {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}


function jsddm_opentimer(listId, activatorId, originalCssClass, callbackmethod) {
    jsddm_canceltimer();
    opentimer = window.setTimeout(function() {
        jsddm_open(listId, activatorId, originalCssClass, callbackmethod);
    }, opentimeout);
}

function jsddm_cancelopentimer() {
    if (opentimer) {
        window.clearTimeout(opentimer);
        opentimer = null;
    }
}





function DropDownList_Show(listId) {
    DropDownList_Show(listId, null, null)
}
function DropDownList_Show(listId, activatorId, originalCssClass) {
    jQuery('#' + listId).parent().parent().unbind('mouseleave');
    if (jQuery('#' + listId).css('display') == 'block') {
        if (activatorId && originalCssClass)
            jQuery('#' + activatorId).attr('class', originalCssClass);
        jQuery('#' + listId).slideUp('fast');
    } else {
        if (activatorId && originalCssClass)
            jQuery('#' + activatorId).attr('class', originalCssClass + '_hover');
        jQuery('#' + listId).parent().parent().click('mouseleave', function() { DropDownList_Show(listId, activatorId, originalCssClass) })
        jQuery('#' + listId).slideDown('fast');
    }
}

function DropDownList_redirect(url, listId) {
    DropDownList_Show(listId);
    document.location = url;
}

///////////////////////////////////////////////////////////////////




//////////////////////EFFECT FADE////////////////////
var lock = true;
jQuery(document).ready(function() {
    if (lock) {
        lock = false;
        jQuery(".EffectFade > a").mouseover(function() {
            jQuery(this).stop();
            jQuery(this).animate({
                opacity: "0.6"
            }, 300)
        });
        lock = true;
    }
    if (lock) {
        jQuery(".EffectFade > a").mouseout(function() {
            jQuery(this).stop();
            jQuery(this).animate({
                opacity: "1"
            }, 300)
        });
    }
});

/////////////////////////////////////////////////////






///////////////////////COOKIES/////////////////////////
function newSessionCookie(nom, contenu) {
    document.cookie = nom + "=" + escape(contenu) + "; path=/";
}

function newExpiringCookie(nom, contenu, jours) {
    var expireDate = new Date();
    expireDate.setTime(expireDate.getTime() + jours * 24 * 3600 * 1000);
    document.cookie = nom + "=" + escape(contenu) + ";expires=" + expireDate.toGMTString() + "; path=/";
}

function readCookie(nom) {
    var deb, fin;
    deb = document.cookie.indexOf(nom + "=");
    if (deb >= 0) {
        deb += nom.length + 1;
        fin = document.cookie.indexOf(";", deb);
        if (fin < 0)
            fin = document.cookie.length;
        return unescape(document.cookie.substring(deb, fin));
    }
    return "";
}

function deleteCookie(nom) {
    newExpiringCookie(nom, "", -1);
}

function deleteDomainCookie(nom, domain) {
    var expireDate = new Date();
    expireDate.setTime(expireDate.getTime() + -1 * 24 * 3600 * 1000);
    document.cookie = nom + "=" + escape("") + ";expires=" + expireDate.toGMTString() + "; path=/; domain=" + domain + ";";
}

///////////////////////////////////////////////////////////////////


///////////////////////PACKAGE FROM VALIDATOR/////////////////////////

function validatePackageDate(source, arguments) {
    if ((arguments.Value == null) || (arguments.Value.length <= 0)) {
        arguments.IsValid = false;
        return false;
    } else {
        arguments.IsValid = true;
        return true;

        var array = arguments.Value.split('/');
        var myDate;

        if (array[0].length > 1 && array[0].startsWith('0'))
            array[0] = array[0].substr(1, 2);
        if (array[1].length > 1 && array[1].startsWith('0'))
            array[1] = array[1].substr(1, 2);
        if (array[2].length > 1 && array[2].startsWith('0'))
            array[2] = array[2].substr(1, 2);

        if (array.length == 3) {
            switch (getLanguageId()) {
                default:
                case 1: //FR
                    myDate = new Date(parseInt(array[2]), parseInt(array[1]) - 1, parseInt(array[0]));
                    break;
                case 2: //EN
                    myDate = new Date(parseInt(array[2]), parseInt(array[0]) - 1, parseInt(array[1]));
                    break;
            }

            today = new Date();

            if (myDate <= today) {
                arguments.IsValid = true;
                return true;
            } else {
                arguments.IsValid = false;
                return false;
            }
        } else {
            arguments.IsValid = false;
            return false;
        }
    }
}

///////////////////////////////////////////////////////////////////



///////////////////////////ADDRESS ////////////////////////////////

function getZoomFromAccuracy(accuracy) {
    var tabZoom = new Array(2, 4, 6, 10, 12, 13, 16, 16, 17, 18);
    return tabZoom[accuracy];
}

///////////////////////////////////////////////////////////////////



///////////////////////USER FROM VALIDATOR/////////////////////////

function validateEmail(source, arguments) {
    if ((arguments.Value == null) || (arguments.Value.length <= 0)) {
        arguments.IsValid = false;
        return false;
    } else {
        var regex = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
        if (regex.test(arguments.Value)) {
            arguments.IsValid = true;
            return true;
        } else {
            arguments.IsValid = false;
            return false;
        }
    }
}

function validatePassword(source, arguments) {
    if ((arguments.Value == null) || (arguments.Value.length <= 0)) {
        arguments.IsValid = false;
        return false;
    } else {
        var regex = new RegExp(/^.{6,}/gi);
        if (regex.test(arguments.Value)) {
            arguments.IsValid = true;
            return true;
        } else {
            arguments.IsValid = false;
            return false;
        }
    }
}

function validateUsername(source, arguments) {
    if ((arguments.Value == null) || (arguments.Value.length <= 5)) {
        arguments.IsValid = false;
        return false;
    } else {
        var regex = new RegExp(/^([a-zA-Z0-9_\.\-])+$/gi);
        if (regex.test(arguments.Value)) {
            arguments.IsValid = true;
            return true;
        } else {
            arguments.IsValid = false;
            return false;
        }
    }
}

function validateUrl(source, arguments) {
    if ((arguments.Value == null) || (arguments.Value.length <= 5)) {
        arguments.IsValid = false;
        return false;
    } else {
        var regex = new RegExp(/(http\:\/\/|https\:\/\/|ftp\:\/\/)+(([a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(\/[a-zA-Z0-9%:\/-_\?\'.~]*)?/gi);
        if (regex.test(arguments.Value)) {
            arguments.IsValid = true;
            return true;
        } else {
            arguments.IsValid = false;
            return false;
        }
    }
}

function validateBirthdate(source, arguments) {
    if ((arguments.Value == null) || (arguments.Value.length <= 0)) {
        arguments.IsValid = false;
        return false;
    } else {
        arguments.IsValid = true;
        return true;

        var array = arguments.Value.split('/');
        var myDate;

        if (array[0].length > 1 && array[0].startsWith('0'))
            array[0] = array[0].substr(1, 2);
        if (array[1].length > 1 && array[1].startsWith('0'))
            array[1] = array[1].substr(1, 2);
        if (array[2].length > 1 && array[2].startsWith('0'))
            array[2] = array[2].substr(1, 2);

        if (array.length == 3) {
            switch (getLanguageId()) {
                default:
                case 1: //FR
                    myDate = new Date(parseInt(array[2]), parseInt(array[1]) - 1, parseInt(array[0]));
                    break;
                case 2: //EN
                    myDate = new Date(parseInt(array[2]), parseInt(array[0]) - 1, parseInt(array[1]));
                    break;
            }

            today = new Date();
            today.setDate(new Date().getDate() - 1);

            if (myDate < today) {
                arguments.IsValid = true;
                return true;
            } else {
                arguments.IsValid = false;
                return false;
            }
        } else {
            arguments.IsValid = false;
            return false;
        }
    }
}

var usernameExists = false;
function validateUsernameExists(source, arguments) {
    if (usernameExists) {
        arguments.IsValid = false;
        return false;
    } else {
        arguments.IsValid = true;
        return true;
    }
}

var usermailExists = false;
function validateUsermailExists(source, arguments) {
    if (usermailExists) {
        arguments.IsValid = false;
        return false;
    } else {
        arguments.IsValid = true;
        return true;
    }
}




///////////////////////////////////////////////////




///////////////////////AJAX////////////////////////

var xmlHttp = getNewHTTPObject();

function getNewHTTPObject() {
    var xmlhttp;
    /** Special IE only code ... */
    /*@cc_on
    @if (@_jscript_version >= 5)
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (E) {
            xmlhttp = false;
        }
    }
    @else
             xmlhttp = false;
        @end
    @*/

    /** Every other browser on the planet */
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        try {
            xmlhttp = new XMLHttpRequest();
        }
        catch (e) {
            xmlhttp = false;
        }
    }

    return xmlhttp;
}

function doAjaxRequest(url, data, callback, isJSON) {
    try {
        xmlHttp = getNewHTTPObject();
        xmlHttp.open('POST', url, true);
        xmlHttp.onreadystatechange = function() {
            if (self.xmlHttp.readyState == 4) {
                var response = '';
                if (isJSON) {
                    var jsonStr = self.xmlHttp.responseText;
                    var json = eval("(" + jsonStr + ')')
                    if (json && json.d)
                        response = json.d;
                    else
                        response = self.xmlHttp.responseText;
                } else {
                    var xmlDoc = self.xmlHttp.responseXML;
                    if (xmlDoc) {
                        var responseElement = xmlDoc.getElementsByTagName("string")[0];
                        if (responseElement && responseElement.firstChild) {
                            response = responseElement.firstChild.nodeValue;
                        } else {
                            response = self.xmlHttp.responseText;
                        }
                    } else {
                        response = self.xmlHttp.responseText;
                    }
                }
                eval(callback + "('" + response + "');");
            }
        }
        if (isJSON)
            xmlHttp.setRequestHeader('Content-Type', 'application/json');
        else
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlHttp.send(data);
    } catch (E) {
    }
}

///////////////////////////////////////////////////






///////////////// Keywords jQuery//////////////////

function checkIfIsEmpty(element) {
    return element.value.length > 0
}


///////////////////////////////////////////////////


//////

function getPackagesData(url) {
    try {
        xmlHttp = getNewHTTPObject();
        xmlHttp.open('POST', url, true);
        xmlHttp.onreadystatechange = function() {
            if (self.xmlHttp.readyState == 4) {
                var response;

                var xmlDoc = self.xmlHttp.responseXML;
                if (xmlDoc) {
                    response = xmlDoc
                } else {
                    response = self.xmlHttp.responseText;
                }

                getPackagesData_callback(self.xmlHttp.responseXML);
            }
        }
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlHttp.send('');
    } catch (E) {
    }
}

//////

/////////////COMMENTS///////////

function CommentClearDefaultTxt(element, defaultTxt) {
    if (element.value == defaultTxt) {
        element.value = "";
    }
}



////////////////////////////////////
function setIframeHeight(iframeId, forceHeight) {
    var iframeEl = document.getElementById ? document.getElementById(iframeId) : document.all ? document.all[iframeId] : null;
    if (iframeEl) {
        iframeEl.style.height = "auto"; // helps resize (for some) if new doc shorter than previous
        var h = alertSize();
        var new_h = (h - 148);
        if (forceHeight)
            new_h += forceHeight;
        iframeEl.style.height = new_h + "px";
    }
}

function alertSize() {
    var myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myHeight = document.body.clientHeight;
    }
    //window.alert( 'Height = ' + myHeight );
    return myHeight;
}
function split(response) {
    var reg = new RegExp("[|]+", "g");
    return response.split(reg);
}
function IsValidMail(email) {
    var regex = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
    return (regex.test(email));
}
function SetCookieFacebook_Timeout(uid, status) {
    var date = new Date();
    date.setDate(date.getDate() + 10 * 24 * 3600 * 1000);
    document.cookie = "facebook_session_timeout="
                                  + "uid=" + escape(uid)
                                  + "&fbStatus=" + status.toString()
                                  + ";expires=" + date.toGMTString()
                                  + ";path=/";
}
/////Gallery Right Block pour Editorside

function RightBlockGallery(RightBlockType) {

    jQuery(RightBlockType + ':first').addClass('Display');
    jQuery(RightBlockType + ':first img.lazyevent').trigger('lazyloadimage');
    var setTimeFlag = '';


    function DisplayRightBlock() {
        if (setTimeFlag != RightBlockType) {

            var DisplayFlag = false;
            jQuery(RightBlockType).each(function(index) {

                if (jQuery(this).css('display') == 'block') {

                    jQuery(this).css('display', 'none');
                    DisplayFlag = true;

                    if (jQuery(RightBlockType).length - 1 == index) {


                        jQuery(RightBlockType + ':first').fadeIn('500');

                    }

                } else if (DisplayFlag) {

                    jQuery(RightBlockType + ' img.lazyevent').trigger('lazyloadimage');
                    jQuery(this).fadeIn('500');
                    DisplayFlag = false;

                }

            });

        }
        setTimeout(DisplayRightBlock, 2000);
    }
    jQuery(RightBlockType).mouseenter(function() {
        setTimeFlag = RightBlockType;
    });
    jQuery(RightBlockType).mouseleave(function() {
        setTimeFlag = '';
    });

    setTimeout(DisplayRightBlock, 2000);
}




/////Boite de dialogue

var CSdialogOption = {

    autoOpen: false,
    modal: true,
    closeOnEscape: false,
    resizable: false,
    draggable: false,
    show: 'fade',
    hide: 'fade',
    //zIndex: 2000000,
    width: 350

};


var AlertdialogOption = {
    autoOpen: false,
    modal: true,
    closeOnEscape: true,
    resizable: false,
    draggable: false,
    show: 'fade',
    hide: 'fade',
    //zIndex: 2000000,
    width: 620,
    dialogClass: 'AlertOverlay'
};

var DefaultDialogOption = {
    autoOpen: false,
    modal: true,
    closeOnEscape: true,
    resizable: false,
    draggable: false,
    show: 'fade',
    hide: 'fade'
};


///// qTooltip
function qTooltipGetContent(element, options) {
    var text = options.text || element.attr('alt');
    var title = options.title || element.attr('title');
    var url = element.attr('rel');
    var type = "text";
    var ajax;

    if (url && url.length > 0) {
        text = '<div class="tooltipLoading"></div>';
        type = 'url',
        ajax = {
            url: url,
            type: 'GET',
            beforeSend: function(data, status) {
                return false;
                //this.set('content.text', data);
            }
        };
    } else if (!text)
        return null;

    if (title && title.length > 0 && text && text.length > 0)
        return { text: text, title: title, prerender: true, type: type, ajax: ajax };
    if (text && text.length > 0)
        return { text: text, prerender: true, type: type, ajax: ajax };

    return null;
}

var qTooltipAjaxManager = jQuery.manageAjax.create('qTooltipDynamicLoading', { queue: 'clear' });
function qTooltipInit(filter, position, options, destroy) {

    if (!options)
        options = { show: 'mouseenter', hide: 'mouseleave' };

    if (!filter || filter.length == 0)
        filter = '.qTooltip';

    if (!position || position.length == 0)
        position = 'right';

    jQuery(filter).each(function(i) {
        var myContent = qTooltipGetContent(jQuery(this), options);
        if (!myContent)
            return;
            
        var my;
        var at;
        switch (position) {
            case "top":
                my = 'bottom center';
                at = 'top center';
                break;
            case "center":
                my = 'center center';
                at = 'center center';
                break;
            case "bottom":
                my = 'top center';
                at = 'bottom center';
                break;
            case "left":
                my = 'right center';
                at = 'left center';
                break;
            default:
            case "right":
                my = 'left center';
                at = 'right center';
                break;
        }

        var target = jQuery(this);
        if (options && options.target)
            target = options.target;
        else if (jQuery(this).attr('target') && jQuery(this).attr('target').length > 0 && jQuery('#' + jQuery(this).attr('target')).length > 0)
            target = jQuery('#' + jQuery(this).attr('target'));

        if (destroy)
            var tooltip = jQuery(this).qtip('destroy');
        else
            var tooltip = jQuery(this).qtip({
                content: myContent,
                style: {
                    classes: 'ui-tooltip-shadow ui-tooltip-jtools ' + options.classes,
                    width: options.width
                },
                position: {
                    my: my,
                    at: at,
                    target: target,
                    viewport: options.viewport || jQuery(window)
                },
                show: {
                    delay: options.showDelay || 500,
                    event: options.show,
                    solo: options.solo
                },
                hide: {
                    delay: options.hideDelay || 100,
                    event: options.hide,
                    fixed: true
                },
                events: {
                    show: function(event, api) {
                        var doIt = true;
                        if (options.preventOpening)
                            doIt = options.preventOpening(event, api);
                        if (doIt && api.get('content.ajax').url && api.get('content.ajax').url.length > 0)
                            qTooltipAjaxManager.add({
                                url: api.get('content.ajax').url,
                                success: function(data) {
                                    api.set('content.text', data);
                                }
                            });
                    },
                    hide: function(event, api) {
                        if (api.get('content.ajax').url && api.get('content.ajax').url.length > 0)
                            qTooltipAjaxManager.clear(true);
                    }
                }
            });
    });
}

jQuery(document).ready(function() {
    qTooltipInit(); //default right
    qTooltipInit(null, "top");
});




function userRankBar(v_start, v_user, v_stop) {
    var v_userPercent = Math.round((v_user - v_start) * 100 / (v_stop - v_start));

    jQuery("#Grades_bar2").animate({
        width: v_userPercent + "%"
    }, 1500);
}




(function($) {
    var cache = [];
    // Arguments are image paths relative to the current page.
    $.preLoadImages = function() {
        var args_len = arguments.length;
        for (var i = args_len; i--; ) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    }
})(jQuery)

///////////////////////////////////////////////
//////////////////// AlertDisplay ////////////////////
///////////////////////////////////////////////
var ActiveAlertObject;
function AlertObject(containerElmId, btnAddId, btnDeleteId, btnModifieId, nbSubscriptionsElmId, overlayElmId, isSubscribed, apiUrl, frameUrl, xmlInfos, format, subType) {
    this.ContainerElmId = containerElmId;
    this.BtnAddId = btnAddId;
    this.BtnDeleteId = btnDeleteId;
    this.BtnModifieId = btnModifieId;
    this.NbSubscriptionsElmId = nbSubscriptionsElmId;
    this.OverlayElmId = overlayElmId;
    this.APIUrl = apiUrl;
    this.FrameUrl = frameUrl;
    this.XmlInfos = xmlInfos;
    this.IsSubscribed = (isSubscribed == 'true');
    this.Format = format;
    this.SubType = subType;

    this.initAlert = function(timeout) {
        this.changeDisplay(timeout);
        this.initClick();
        this.initEvents();
    };

    this.changeDisplay = function(timeout) {
        var pending = (timeout && timeout > 0 ? timeout : 0);
        var alertObject = this;
        jQuery('#' + alertObject.ContainerElmId).removeClass('subscribed unsubscribed done');
        if (alertObject.IsSubscribed)
            jQuery('#' + alertObject.ContainerElmId).addClass('subscribed');
        else
            jQuery('#' + alertObject.ContainerElmId).addClass('unsubscribed');

        setTimeout(function() {
            if (alertObject.IsSubscribed)
                jQuery('#' + alertObject.ContainerElmId).addClass('done');
            else
                jQuery('#' + alertObject.ContainerElmId).addClass('done');
        }, pending);
    };

    this.initClick = function() {
        var alertObject = this;
        jQuery('#' + alertObject.BtnAddId).unbind('click');
        jQuery('#' + alertObject.BtnDeleteId).unbind('click');
        jQuery('#' + alertObject.BtnModifieId).unbind('click');

        if (jQuery('#' + alertObject.BtnAddId) && !jQuery('#' + alertObject.ContainerElmId).hasClass('subscribed')) {
            jQuery('#' + alertObject.BtnAddId).click(function() {
                alertObject.UpdateAlertSubscription("CreateAlertSubscription");
            });
        }
        if (jQuery('#' + alertObject.BtnDeleteId) && !jQuery('#' + alertObject.ContainerElmId).hasClass('unsubscribed')) {
            jQuery('#' + alertObject.BtnDeleteId).click(function() {
                if (jQuery('#' + alertObject.ContainerElmId).hasClass('deleteConfirm')) {
                    jQuery('#' + alertObject.ContainerElmId).removeClass('deleteConfirm');
                    alertObject.UpdateAlertSubscription('DeleteAlertSubscription');
                }
                else
                    jQuery('#' + alertObject.ContainerElmId).addClass('deleteConfirm');
            });
        }
        if (jQuery('#' + alertObject.BtnModifieId)) {
            jQuery('#' + alertObject.BtnModifieId).click(function() {
                alertObject.initFramableElement('unknown', 'InitializeOverlay', true);
            });
        }
    };

    this.initEvents = function() {
        var alertObject = this;

        jQuery(document).bind('authchange', function(e, islogin) {
            alertObject.initFramableElement(alertObject.Format, 'ReinitializeAlertDisplay', false);
        });

        jQuery('#' + alertObject.ContainerElmId).bind('AlertSubscriptionChange', function(e, action) {
            if (action == 'UpdateAlertSubscription')
                alertObject.initFramableElement(alertObject.Format, 'ReinitializeAlertDisplay', false);
            else {
                switch (action) {
                    case 'CreateAlertSubscription':
                        alertObject.IsSubscribed = true;
                        break;
                    case 'DeleteAlertSubscription':
                        alertObject.IsSubscribed = false;
                        break;
                }
                alertObject.initAlert(1000);
            }
        });
    };

    this.UpdateAlertSubscription = function(action) {
        var alertObject = this;
        ActiveAlertObject = alertObject;
        jQuery('#' + alertObject.ContainerElmId).addClass('waiting');
        jQuery('#' + alertObject.ContainerElmId).removeClass('error');
        jQuery('#' + alertObject.ContainerElmId).removeClass('done');

        jQuery.ajax({
            url: alertObject.APIUrl + '?Action=' + action,
            type: 'POST',
            data: ({ XmlInfos: alertObject.XmlInfos }),
            dataType: 'html',
            success: function(response) {
                jQuery('#' + alertObject.ContainerElmId).removeClass('waiting');
                if (jQuery.trim(response) == 'NotLogged') {
                    alertObject.initFramableElement('AlertManager_ValidateMail', 'InitializeOverlay', true);
                }
                else if (jQuery.trim(response) == 'OK') {
                    jQuery('#' + alertObject.ContainerElmId).trigger('AlertSubscriptionChange', [action]);
                }
                else if (jQuery.trim(response) == 'ERROR')
                    jQuery('#' + alertObject.ContainerElmId).addClass('error');
            }
        });
    };
    this.ModifieAlertSubscriptionSettings = function(alertSubscriptionInfos) {
        var alertObject = this;
        ActiveAlertObject = alertObject;
        jQuery('#' + alertObject.ContainerElmId).removeClass('error');
        jQuery.ajax({
            url: alertObject.APIUrl + '?Action=UpdateAlertSubscription',
            type: 'POST',
            data: ({
                XmlInfos: alertObject.XmlInfos,
                XmlAlertSubscriptionInfos: alertSubscriptionInfos
            }),
            dataType: 'html',
            success: function(response) {
                if (jQuery.trim(response) == 'OK') {
                    jQuery('#' + alertObject.ContainerElmId).trigger('AlertSubscriptionChange', ['UpdateAlertSubscription']);
                }
                else if (jQuery.trim(response) == 'ERROR')
                    jQuery('#' + alertObject.ContainerElmId).addClass('error');
            }
        });
    };
    this.initFramableElement = function(format, action, openIt, appendToElmId) {
        var alertObject = this;
        jQuery('#' + alertObject.ContainerElmId).addClass('waiting');
        jQuery('#' + alertObject.ContainerElmId).removeClass('error');
        ActiveAlertObject = alertObject;
        jQuery('#' + alertObject.OverlayElmId).remove();
        jQuery.ajax({
            url: alertObject.FrameUrl + '?inner=',
            type: 'POST',
            data: ({ xmlInfos: alertObject.XmlInfos, Format: format, action: action }),
            dataType: 'html',
            success: function(htmlRender) {
                jQuery('#' + alertObject.ContainerElmId).removeClass('waiting');
                if (jQuery.trim(htmlRender) == 'ERROR')
                    jQuery('#' + alertObject.ContainerElmId).removeClass('waiting');
                else {
                    if (appendToElmId) {
                        var oldContent = jQuery('#' + appendToElmId).html();
                        jQuery('#' + appendToElmId).empty();
                        jQuery('#' + appendToElmId).append(htmlRender);
                        jQuery('#' + appendToElmId).append(oldContent);
                    }
                    else if (openIt) {
                        jQuery('#' + alertObject.ContainerElmId).append(htmlRender);
                        jQuery('#' + alertObject.OverlayElmId).dialog(AlertdialogOption);
                        jQuery('#' + alertObject.OverlayElmId).dialog('open');
                    }
                    else {
                        jQuery('#' + alertObject.ContainerElmId).replaceWith(htmlRender);
                    }
                }
            }
        });
    };
}
///////////////////////////////////////////////////////
/////////////////AlertDiapos///////////////////////////
///////////////////////////////////////////////////////
function AlertDiaposObject(containerElmId, frameUrl, xmlParameters, pagingElementId) {
    this.ContainerElementID = containerElmId;
    this.XmlParameters = xmlParameters;
    this.FrameUrl = frameUrl;
    this.PagingElementId = pagingElementId;
    this.InitializeCallBack = function() { };
    this.Initialize = function(appendIt, scrollableElementId, bindScroll, notAddKeyword) {
        var alertDiaposObject = this;
        jQuery('#' + alertDiaposObject.PagingElementId).removeClass('disabled error');
        jQuery('#' + alertDiaposObject.ContainerElementID).addClass('waiting');

        jQuery.ajax({
            url: alertDiaposObject.FrameUrl + '?inner=',
            type: 'POST',
            data: ({
                action: 'InitializeAlertDiapos',
                XmlParameters: alertDiaposObject.XmlParameters,
                AddKeyword: notAddKeyword == true ? '' : 'addKeyword'
            }),
            dataType: 'html',
            success: function(htmlRender) {
                jQuery('#' + alertDiaposObject.ContainerElementID).removeClass("waiting");
                alertDiaposObject.InitializeCallBack.call(htmlRender);
                if (jQuery.trim(htmlRender) == 'ERROR')
                    jQuery('#' + alertDiaposObject.ContainerElementID).addClass("error");
                else if (jQuery.trim(htmlRender).length > 0) {
                    if (scrollableElementId && bindScroll) {
                        bindScrollable(scrollableElementId);
                    }
                    if (appendIt)
                        jQuery('#' + alertDiaposObject.ContainerElementID).append(htmlRender);
                    else
                        jQuery('#' + alertDiaposObject.ContainerElementID).html(htmlRender);
                }
                else {
                    jQuery('#' + alertDiaposObject.PagingElementId).addClass('disabled');
                }
            }
        });
    };
    this.InitializeNext = function(appendIt, scrollableElementId, bindScroll) {
        var alertDiaposObject = this;
        var index1 = alertDiaposObject.XmlParameters.lastIndexOf('<PageNumber>');
        var index2 = alertDiaposObject.XmlParameters.lastIndexOf('</PageNumber>');
        var currentPageNumber = parseInt(alertDiaposObject.XmlParameters.substring(index1 + 12, index2));
        var pageNumber = currentPageNumber + 1;

        var xmlParameters = alertDiaposObject.XmlParameters.replace('<PageNumber>' + currentPageNumber + '</PageNumber>', '<PageNumber>' + pageNumber + '</PageNumber>');
        alertDiaposObject.XmlParameters = xmlParameters;
        alertDiaposObject.Initialize(appendIt, scrollableElementId, bindScroll, true);
    };
}
function bindToAlertSubscriptionEvent(newDiapoSize) {
    jQuery(document).bind("AlertSubscriptionChange", function(e, action) {
        if (action == 'CreateAlertSubscription' || action == 'DeleteAlertSubscription') {
            setTimeout(function() {
                //jQuery('#' + ActiveAlertObject.ContainerElmId).remove();
                //jQuery('#' + ActiveAlertObject.ContainerElmId).addClass('done');
                if (action == 'CreateAlertSubscription') {
                    var container = '';
                    var diapoListSrc = '';
                    var tab = '';
                    switch (ActiveAlertObject.SubType) {
                        case 'Celebrity':
                            container = '_pnlMyCelebritiesAlerts';
                            tab = 'tabCelebritiesAlerts';
                            diapoListSrc = 'MyCelebrities';
                            break;
                        case 'Portfolio':
                            container = '_pnlMyPortfoliosAlerts';
                            tab = 'tabPortfoliosAlerts';
                            diapoListSrc = 'MyPortfolios';
                            break;
                        case 'Category':
                            container = '_pnlMyCategoriesAlerts';
                            tab = 'tabCategoriesAlerts';
                            diapoListSrc = 'MyCategories';
                            break;
                        case 'SubCategory':
                            container = '_pnlMySubCategoriesAlerts';
                            tab = 'tabSubCategoriesAlerts';
                            diapoListSrc = 'MySubCategories';
                            break;
                        case 'Address':
                            container = '_pnlMyAddressesAlerts';
                            tab = 'tabAddressesAlerts';
                            diapoListSrc = 'MyAddresses';
                            break;
                        case 'Keyword':
                            container = '_pnlMyKeywordsAlerts';
                            tab = 'tabKeywordsAlerts';
                            diapoListSrc = 'MyKeywords';
                            break;
                        //                    case 'Group':                                                                                                                                               
                        //                        container = '_pnlMyGroupsAlerts';                                                                                                                                              
                        //                        tab = 'tabGroupsAlerts';                                                                                                                                              
                        //                        diapoListSrc = 'MyGroups';                                                                                                                                                
                        //                        break;                                                                                                                               
                    }
                    if (!ActivateAlertsTab(container, tab, diapoListSrc))
                        ActiveAlertObject.initFramableElement(newDiapoSize, 'ReinitializeAlertDisplay', true, container);
                    TopAlertsDiapos.Initialize();
                    SuggestAlertsDiapos.Initialize();

                }
            }, 1000);
        }
    });
}
function ConstructAlertDiaposXmlParameters(diaposize, pagesize, pagenumber, diapoListSource, format, other) {
    var xmlParameters = '<Parameters>';
    xmlParameters += '<DiapoSize>' + diaposize + '</DiapoSize>';
    xmlParameters += '<PageSize>' + pagesize + '</PageSize>';
    xmlParameters += '<PageNumber>' + pagenumber + '</PageNumber>';
    xmlParameters += '<DiapoListSource>' + diapoListSource + '</DiapoListSource>';
    xmlParameters += '<Format>' + format + '</Format>';
    if (other) xmlParameters += other;
    xmlParameters += '</Parameters>';
    return xmlParameters;
}
/////////////////////////////////////////////
//////////////////// AddressIndex ///////////////
/////////////////////////////////////////////
function AddressIndexObject(containerElmId, jsonInfosObject) {
    this.ContainerElmId = containerElmId;
    this.IsSelected = false;
    this.JsonInfosObject = jsonInfosObject;
    this.Initialize = function() {
        this.changeDisplay();
        this.initClick();
        this.initEvents();
    };

    this.changeDisplay = function() {
        jQuery('#' + this.ContainerElmId).html(this.JsonInfosObject.FormattedAddress);
        jQuery('#' + this.ContainerElmId).removeClass('selected unselected');
        if (this.IsSelected)
            jQuery('#' + this.ContainerElmId).addClass('selected');
        else
            jQuery('#' + this.ContainerElmId).addClass('unselected');
    };

    this.initClick = function() {
        var addressIndexObject = this;
        jQuery('#' + addressIndexObject.ContainerElmId).unbind('click');
        if (addressIndexObject.IsSelected == false) {
            jQuery('#' + addressIndexObject.ContainerElmId).click(function() {
                jQuery('#' + addressIndexObject.ContainerElmId).trigger("AddressIndexesSelectedItemChanged", addressIndexObject);
            });
        }
    };

    this.initEvents = function() {
        var addressIndexObject = this;
        jQuery(document).bind("AddressIndexesSelectedItemChanged", function(e, addressIndexO) {
            addressIndexObject.IsSelected = (addressIndexObject.ContainerElmId == addressIndexO.ContainerElmId);
            addressIndexObject.changeDisplay();
            addressIndexObject.initClick();
        });
    };
}

function AddressIndexDiaposObject(containerElmId, jsonInfos) {
    this.ContainerElmId = containerElmId;
    this.JsonInfos = jsonInfos;
    this.SelectedAddressIndexObject;
    this.Initialize = function() {
        jQuery('#' + this.ContainerElmId).empty();
        var jsonAddressesObject = JSON.parse(this.JsonInfos);
        if (jsonAddressesObject.Addresses.length > 0) {
            for (i = 0; i < jsonAddressesObject.Addresses.length; i++) {
                jQuery('#' + this.ContainerElmId).append('<div id="_pnlRstrictionAdrressIndex_' + i + '"></div>');
                new AddressIndexObject('_pnlRstrictionAdrressIndex_' + i, jsonAddressesObject.Addresses[i]).Initialize();
            }
        }
        this.initEvents();
    };
    this.initEvents = function() {
        var addressIndexDiaposObject = this;
        jQuery(document).bind("AddressIndexesSelectedItemChanged", function(e, addressIndexO) {
            addressIndexDiaposObject.SelectedAddressIndexObject = addressIndexO;
        });
    };
}
/////////////////////////////////////////////
//////////////////// Favorite ///////////////
/////////////////////////////////////////////
function FavoriteObject(containerElmId, textElmId, cookieId, apiUrl, frameUrl, packageId, txtInvitationToLogin, isSubscribed) {
    this.ContainerElmId = containerElmId;
    this.TextElmId = textElmId;
    this.CookieId = cookieId;
    this.ApiUrl = apiUrl;
    this.FrameUrl = frameUrl;
    this.PackageId = packageId;
    this.LoginText = txtInvitationToLogin;
    this.IsSubscribed = (isSubscribed == 'true'); //(readCookie(this.CookieId) && readCookie(this.CookieId) != '') ? true : false;

    this.initFavorite = function() {
        this.changeDisplay();
        this.initClick();
        this.initEvents();
    };

    this.changeDisplay = function() {
        jQuery('#' + this.ContainerElmId).removeClass('subscribed unsubscribed');
        if (this.IsSubscribed)
            jQuery('#' + this.ContainerElmId).addClass('subscribed');
        else
            jQuery('#' + this.ContainerElmId).addClass('unsubscribed');
    };

    this.initClick = function() {
        var fvObject = this;
        jQuery('#' + fvObject.ContainerElmId).unbind('click');
        jQuery('#' + fvObject.ContainerElmId).click(function() {
            fvObject.updateFavorite();
        });
    };

    this.initEvents = function() {
        var fvObject = this;
        jQuery('#' + fvObject.ContainerElmId).bind("FavoriteStatusChange", function(e, jsonFavorite, action) {
            var jsonObj = jQuery.parseJSON(jsonFavorite);
            if (action == "CreateFavorite") {
                //newExpiringCookie(fvObject.CookieId, jsonObj.ID_User, 30);
                fvObject.IsSubscribed = true;
            }
            else if (action == "DeleteFavorite") {
                // deleteCookie(fvObject.CookieId);
                fvObject.IsSubscribed = false;
            }
            jQuery('#' + fvObject.TextElmId).html(jsonObj.FavoritesCount);
            fvObject.changeDisplay();
            fvObject.initClick();
        });
    };

    this.updateFavorite = function() {
        action = '';
        var fvObject = this;
        if (fvObject.IsSubscribed) {
            if (jQuery('#' + this.ContainerElmId).hasClass('confirm')) {
                action = 'DeleteFavorite';
                jQuery('#' + fvObject.ContainerElmId).removeClass("confirm");
            }
            else
                jQuery('#' + fvObject.ContainerElmId).addClass('confirm');
        }
        else
            action = 'CreateFavorite'
        if (action != '') {
            //jQuery('#' + fvObject.ContainerElmId).unbind('click');
            jQuery('#' + fvObject.ContainerElmId).addClass('waiting');
            jQuery.ajax({
                url: fvObject.ApiUrl + '?Action=' + action,
                type: 'POST',
                data: ({ id_Package: fvObject.PackageId }),
                dataType: 'html',
                success: function(jsonResponse) {
                    jQuery('#' + fvObject.ContainerElmId).removeClass("waiting");
                    jQuery('#' + fvObject.ContainerElmId).removeClass("confirm");
                    if (jsonResponse == 'notLogged')
                        alert(fvObject.LoginText);
                    if (jsonResponse != '')
                        jQuery('#' + fvObject.ContainerElmId).trigger("FavoriteStatusChange", [jsonResponse, action]);
                }
            });
        }
    };
}





/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode: function(input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode: function(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
///////////////// FORM /////////////////////

var formSubmit = true;
function initForm(options) {
    var parentForm = "#" + (options.aspFormID || options.inputToSubmitContainerID);
    var currentForm = "#" + options.inputToSubmitContainerID;
    var button = "#" + options.submitButtonID;
    var url = options.apiUrl;
    var doneAutoHideTime = options.doneAutoHideTime || 1500;
    var startingSubmitCallbackMethod = options.startingSubmitCallbackMethod;
    var beforeSubmitCallbackMethod = options.beforeSubmitCallbackMethod;
    var successCallbackMethod = options.successCallbackMethod;

    jQuery(parentForm).submit(function() { return formSubmit });
    jQuery(parentForm).validate({
        rules: options.rules,
        messages: options.messages,
        errorClass: "errormessage",
        onkeyup: false,
        ignore: options.ignore,
        errorClass: 'error',
        validClass: 'valid',
        errorPlacement: function(error, element) {
            var pos = ['right', 'left', 'top', 'bottom'];
            var my = ['left center', 'right center', 'bottom center', 'top center'];
            var at = ['right center', 'left center', 'top center', 'bottom center'];

            var elem = jQuery(element);

            var position = 'right';
            var target = elem;
            if (options.messages) {
                var msg = eval('options.messages.' + jQuery(elem).attr('name'));
                if (msg && msg.errors) {
                    position = msg.errors.position;
                    target = msg.errors.target || target;
                }
            }

            var idx = pos.indexOf(position);
            if (idx < 0 || pos.length <= idx)
                idx = 0;

            // Check we have a valid error message
            if (!error.is(':empty') && target.is(':visible')) {
                // Apply the tooltip only if it isn't valid
                target.parents('*:first').removeClass('validParent');
                target.parents('*:first').addClass('errorParent');
                //elem.focus();
                elem.filter(':not(.valid)').qtip({
                    overwrite: false,
                    content: error,
                    position: {
                        my: my[idx],
                        at: at[idx],
                        target: target,
                        viewport: options.viewport || jQuery(window)
                    },
                    show: {
                        event: false,
                        ready: true
                    },
                    hide: false,
                    style: {
                        width: options.tooltipWidth,
                        classes: 'ui-tooltip-red ' + options.tooltipClasses // Make it red... the classic error colour!
                    }
                })

                // If we have a tooltip on this element already, just update its content
               .qtip('option', 'content.text', error);
            }

            // If the error is empty, remove the qTip
            else {
                elem.parents('*:first').removeClass('errorParent');
                elem.parents('*:first').addClass('validParent');
                elem.qtip('destroy');
            }
        },
        success: jQuery.noop // Odd workaround for errorPlacement not firing!
    });
    jQuery(currentForm + ' input').bind('keypress', function(e) {
        formSubmit = false;
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            jQuery(button).click();
        }
    });

    jQuery(currentForm + ' input').each(function(i) {
        var that = this;
        if (options.messages) {
            var elem;
            try { elem = eval('options.messages.' + jQuery(this).attr('name')); } catch (E) { }
            if (elem && elem.info)
                qTooltipInit(jQuery(currentForm + ' input[name="' + jQuery(this).attr('name') + '"]').parents('*:first'),
                    elem.info.position,
                    {
                        show: 'focusin',
                        hide: 'focusout',
                        title: elem.info.title,
                        text: elem.info.text,
                        target: elem.info.target || jQuery(currentForm + ' input[name="' + jQuery(this).attr('name') + '"]'),
                        viewport: options.viewport,
                        width: options.tooltipWidth,
                        classes: options.tooltipClasses,
                        preventOpening: function(event, api) {
                            if (jQuery(that).hasClass('error')) {
                                event.preventDefault();
                                return false;
                            }
                            return true;
                        }
                    }
                );
        }
        if (options.behaviors) {
            var elem = eval('options.behaviors.' + jQuery(this).attr('name'));
            if (elem && elem.disableIfNotEmpty == true && jQuery(currentForm + ' input[name="' + jQuery(this).attr('name') + '"]').val().length > 0) {
                jQuery(currentForm + ' input[name="' + jQuery(this).attr('name') + '"]').prop('disabled', true);
                jQuery(currentForm + ' input[name="' + jQuery(this).attr('name') + '"]').addClass('disabled');
            }
        }
    });
    jQuery(button).click(function() {
        jQuery(currentForm).removeClass('error');
        jQuery(currentForm).removeClass('done');
        jQuery(currentForm).addClass('loading');
        setTimeout(function() {
            if (jQuery(parentForm).valid()) {
                jQuery(button).prop('disabled', true);
                var inputsArr;

                if (startingSubmitCallbackMethod)
                    startingSubmitCallbackMethod();

                if (parentForm != currentForm) {
                    jQuery(parentForm).ajaxSubmit({
                        beforeSubmit: function(arr, form, options) {
                            inputsArr = arr;
                            for (i = 0; i < arr.length; i++) {
//                                jQuery(parentForm + ' *[name="' + arr[i].name + '"]').prop('disabled', true);
//                                if (jQuery(parentForm + ' ' + currentForm + ' *[name="' + arr[i].name + '"]').length > 0)
//                                    jQuery(parentForm + ' ' + currentForm + ' *[name="' + arr[i].name + '"]').prop('disabled', false);
                                if (jQuery(parentForm + ' ' + currentForm + ' *[name="' + arr[i].name + '"]').length == 0)
                                    jQuery(parentForm + ' *[name="' + arr[i].name + '"]').prop('disabled', true);
                            }
                            return false;
                        }
                    });
                }
                jQuery(parentForm).ajaxSubmit({
                    url: url,
                    type: 'POST',
                    dataType: 'text',
                    success: function(responseText, statusText, xhr, form) {
                        jQuery(currentForm).removeClass('loading');
                        formSubmit = true;
                        jQuery(button).prop('disabled', false);

                        jQuery(currentForm).addClass('done');
                        if (doneAutoHideTime)
                            setTimeout(function() {
                                jQuery(currentForm).removeClass('done');
                            }, doneAutoHideTime);
                        if (successCallbackMethod)
                            successCallbackMethod(responseText, statusText, xhr, form);
                    },
                    error: function(responseText, statusText, xhr, form) {
                        jQuery(currentForm).removeClass('loading');
                        formSubmit = true;
                        jQuery(button).prop('disabled', false);

                        jQuery(currentForm).addClass('error');
                    },
                    beforeSubmit: function(arr, form, options) {
                        var doIt = true;
                        if (beforeSubmitCallbackMethod)
                            doIt = beforeSubmitCallbackMethod(arr, form, options) || true;

//                        if (inputsArr)
//                            for (i = 0; i < inputsArr.length; i++) {
//                            jQuery(parentForm + ' *[name="' + inputsArr[i].name + '"]').prop('disabled', false);
//                        }
                        return doIt;
                    },
                    complete: function() {
                    }
                });
            } else {
                jQuery(currentForm).addClass('error');
                jQuery(currentForm).removeClass('loading');
            }
        }, 500);
    });
}


function clearFormElements(selector) {

    jQuery(selector).find(':input').each(function() {
        switch (this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
            case 'file':
                jQuery(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });

}


//////////////// IMAGE loading /////////////

function getDOMImageSize(selector, callbackMethod) {
    getUrlImageSize(jQuery(selector).attr("src"), callbackMethod);
}
function getUrlImageSize(url, callbackMethod) {
    jQuery("<img/>")
		.attr("src", url)
		.load(function() {
		    if (callbackMethod) {
		        callbackMethod({ width: this.width, height: this.height });
		    }
		});
}



///// zoom sur diapo //////
function initZoom(destroy) {
    jQuery('.zoomer').each(function() {
        var text = jQuery(this).find('.zoomerBox').html();
        jQuery(this).find('.zoomerBtn').each(function() {

            qTooltipInit(this, 'center', {
                solo: true,
                text: text,
                showDelay: 200
            }, destroy);
            jQuery(this).click(function(event) { event.preventDefault(); })
        });
    });
};

jQuery(document).ready(function() {
    toggleZoomer(readCookie('toggleZoomer'));
});

function forceZoomerClose(rootFilter) {
    jQuery(rootFilter).find('.zoomerBtn').qtip().hide();
}

function toggleZoomer(zoomVal) {

    if (zoomVal == 'op_yes') {
        initZoom(true);
        jQuery('#_zoomer option[value=op_no]').removeAttr('selected');
        jQuery('#_zoomer option[value=op_yes]').attr('selected', 'selected');
        newExpiringCookie('toggleZoomer', 'op_yes', 30);
    } else { // op_no
        initZoom(false);
        jQuery('#_zoomer option[value=op_yes]').removeAttr('selected');
        jQuery('#_zoomer option[value=op_no]').attr('selected', 'selected');
        newExpiringCookie('toggleZoomer', 'op_no', 30);
    }
}



///// file checkboxes //////

function changeCheck(filter, isChecked) {
    jQuery(filter).each(function() {
        if (typeof (isChecked) == 'undefined')
            this.checked = !this.checked;
        else
            this.checked = isChecked;
    });
}


function addToCart(checkBoxFilter, isLB) {
    jQuery(checkBoxFilter).each(function() {
        if (this.checked) {
            var parent = jQuery(this).parents()[0];
            var button;
            if (isLB) {
                button = jQuery(parent).find('.CD_addToLB')
            } else {
                button = jQuery(parent).find('.CD_addToCart')
            }
            button.click();
        }
    });
}

