/*
all AJAX actions
*/
var FotoliaAjaxActions = {
    obj: Object,

    init: function() {
        if (
            !document.getElementById ||
            !document.createElement ||
            !document.getElementsByTagName
        ) {
            return;
        }

        var i,j;

        // add events to Ajax links
        var current = document.getElementsByTagName('a');
        var curLen = current.length;


        for (j = 0; j < curLen; j++) {
            // must redefine regexp because of reuse
            var regexp = new RegExp('^https?://[A-Za-z0-9_\\.]+/Ajax/([A-Za-z0-9]+)', 'gi');
            var results = regexp.exec(current[j].href);
            if (!results) {
                continue;
            }

            // replace onclick
            current[j].onclick = FotoliaAjaxActions.basicClick;
        }
    },

    basicClick: function(e) {
        url = this.href;

        var pars = '';
        var myAjax = new Ajax.Request();

        myAjax.setOptions(
            {
                method: 'get',
                parameters: pars,
                onComplete: FotoliaAjaxActions.XHRResponseTextCallback
            }
        );

        // reference to source
        myAjax.sourceObject = this;

        myAjax.request(url);

        return false;
    },

    radioClick: function(e) {

        url = this.href;

        var pars = '';
        var myAjax = new Ajax.Request();
        myAjax.setOptions(
            {
                method: 'get',
                parameters: pars,
                onComplete: FotoliaAjaxActions.XHRResponseTextCallback
            }
        );

        // reference to source
        myAjax.sourceObject = this;

        myAjax.request(url);

        return true;
    },

    XHRResponseTextCallback: function(XHR, eJSON, origin) {
        try {
            eval(XHR.responseText);
        } catch (e) {
            var s = '';
            for (i in e) {
                s += i + ' = ' + e[i] + "\n";
            }
        }
    }
}

var FotoliaTooltip = {
    cache : {},
    init: function() {
        if (
            !document.getElementById ||
            !document.createElement ||
            !document.getElementsByTagName
        ) {
            return;
        }

        var current = document.getElementsByTagName('img');
        var curLen = current.length;

        for (var j = 0; j < curLen; j++) {
            // we must redefine regexps (JS bug)
            var regexp_photos_mini = new RegExp('\/[0-9\/-]+\/(30|110)_F_');

            if (!current[j].src.match(regexp_photos_mini)) {
                continue;
            }

            var regexp = new RegExp('\/(30|110)_F_');
            var largeSrc = current[j].src.replace(regexp, '/400_F_');

            current[j].setAttribute('largeSrc', largeSrc);

            var title = current[j].getAttribute('title');
            // remove title
            current[j].setAttribute('title', '');

            if(current[j].getAttribute('tooltip')) {
                addEvent(current[j], 'mouseover', this.show);
                var ident = 'tooltip:' + current[j].getAttribute('tooltip') + ':' + current[j].getAttribute('id');
                var tip = '<div id="' + ident + '">' + _('Loading ...') + '</div>';
            } else {
                var tip = '<div class="tool"><img src="' + largeSrc + '" /></div>';
            }

            new Tooltip(current[j], tip, {'html': true, 'classname': 'FotoliaTooltipObject'});
        }
    },

    show: function () {
        var tooltip = this.getAttribute('tooltip');
        var id = this.getAttribute('id');
        var cache_key = tooltip + ':' + id;
        if (FotoliaTooltip.cache[cache_key]) {
            return;
        }
        FotoliaTooltip.cache[cache_key] = true;
        var url;
        if (tooltip.substring(0, 1) == '/') {
            url = '/Tooltip' + tooltip;
        } else {
            url = '/Tooltip' + '/' + tooltip;
        }

        // update html node
        new Ajax.Updater('tooltip:' + tooltip + ':' + id, url, {evalScripts:true});
    }
}

/*
Zoom on 400px images

based on http://valid.tjp.hu/zoom2/index_en.html + events and crop on server
create several FotoliaZoom object on onload events
*/
var FotoliaZooms = {
    containers: new Array(),

    init: function() {

        if (
            !document.getElementById ||
            !document.createElement ||
            !document.getElementsByTagName
        ) {
            return;
        }

        var current = document.getElementsByTagName('img');
        var curLen = current.length;

        var zoom_present = false;

        for (var j = 0; j < curLen; j++) {
            var regexp_photos_mini = new RegExp('\/(jpg|photos_mini)\/.*\/(300|400)_F_');

            if (!current[j].src.match(regexp_photos_mini)) {
                continue;
            }

            FotoliaZooms.createNewZoom(current[j]);
            zoom_present = true;
        }

        if (zoom_present) {
            addEvent(window.document, 'click', function() { FotoliaZooms.reinit(); });
        }
    },

    createNewZoom: function(img)
    {
        // zoom ratio for each new click
        if (zoom_ratio = img.getAttribute('zoom_ratio')) {
            zoom_ratio = Number(zoom_ratio);
            if (zoom_ratio == 0) {
                return;
            }
        } else {
            return;
        }

        if (zoom_depth_max = img.getAttribute('zoom_depth_max')) {
            zoom_depth_max = Number(zoom_depth_max);
        } else {
            return;
        }

        var zoom = new FotoliaZoom(img, zoom_ratio, zoom_depth_max);
        zoom.create();
    },

    reinit: function()
    {
        for (var i = 0, l = FotoliaZooms.containers.length; i < l; i++) {
            var container = FotoliaZooms.containers[i];

            // reinit
            if (typeof(container.originalSrc) == 'undefined') {
                continue;
            }

            container.img.src = container.originalSrc;

            container.img.style.left = '0px';
            container.img.style.top = '0px';
            container.img.width = container.w;
            container.img.height = container.h;

            container.FotoliaZoom.zoomDepth = 1;

            container.baseX = 0;
            container.baseY = 0;

            container.baseLeft = 0;
            container.baseTop = 0;

            container.FotoliaZoom.zoomDepth = 1;
        }
    }
}


function FotoliaZoom(img, zoom_ratio, zoom_depth_max)
{
    this.img = img;

    // zoom ratio for each new click
    this.zoomRatio = zoom_ratio
    this.zoomDepthMax = zoom_depth_max + 1;

    // clip border
    this.bordersize = 1;

    // clip border
    this.outbordersize = 1;

    // ratio of the clip box
    this.ratio = 1 / this.zoomRatio;

    this.zoomDepth = 0;

    this.loading = false;
}

FotoliaZoom.prototype.create = function()
{
    // add events, only on jpg
    var regexp_tb = new RegExp('\/(jpg|photos_mini)\/.+\/(300|400)_F_');

    if (!this.img.src.match(regexp_tb)) {
        return;
    }

    // create container
    var div = document.createElement('div');
    div.id = 'FotoliaZoom:' + this.img.src;

    div.style.width = this.img.width + 'px';
    div.style.height = this.img.height + 'px';

    var newImage = this.img.cloneNode(false);
    newImage.originalSrc = newImage.src;
    newImage.id = 'img:' + this.img.src;
    newImage.setAttribute('title', '');

    // create clip
    var divClip = document.createElement('div');

    Element.setStyle(
        div,
        {
            position: 'relative',
            overflow: 'hidden'
        }
    );

    Element.setStyle(
        divClip,
        {
            position: 'absolute',
            width: Math.round(this.img.width * this.ratio) + 'px',
            height: Math.round(this.img.height * this.ratio) + 'px',
            border: '1px solid #777777',
            borderWidth: Math.round(this.bordersize) + 'px'
        }
    );

    Element.hide(divClip);

    // append child
    div.appendChild(newImage);
    div.appendChild(divClip);

    // replace original image
    this.img.parentNode.replaceChild(div, this.img);

    Element.addClassName(div, 'FotoliaZoom');
    Element.addClassName(divClip, 'FotoliaZoomClip');

    // name references
    this.container = div;
    this.container.img = newImage;
    this.container.clip = divClip;

    this.container.FotoliaZoom = this;

    addEvent(this.container, 'mouseover', this.onmouseover);
    addEvent(this.container, 'mousemove', this.onmousemove);
    addEvent(this.container, 'mouseout', this.onmouseout);
    addEvent(this.container, 'click', this.onclick);

    FotoliaZooms.containers.push(this.container);
}

// for these functions, 'this' is the container
FotoliaZoom.prototype.onmousemove = function(e)
{
    var xCord;
    var yCord;

    if (document.captureEvents) {
        xCord = e.pageX;
        yCord = e.pageY;
    } else if (window.event.clientX) {
        xCord = window.event.clientX + document.documentElement.scrollLeft;
        yCord = window.event.clientY + document.documentElement.scrollTop;
    }

    // reference to clip
    var clip = this.clip;

    var left = Math.ceil(xCord - this.xCord - clip.w / 2);
    var top = Math.ceil(yCord - this.yCord - clip.h / 2);

    if (left < 0) {
        left = 0;
    } else if (left >= (this.w - clip.w)) {
        left = this.w - clip.w - this.FotoliaZoom.bordersize * 2;
    }

    if (top < 0) {
        top = 0;
    } else if (top >= (this.h - clip.h)) {
        top = this.h - clip.h - this.FotoliaZoom.bordersize * 2;
    }

    if (isNaN(top)) {
        top = 0;
    }

    if (isNaN(left)) {
        left = 0;
    }

    Element.setStyle(
        clip,
        {
            top: top + 'px',
            left: left + 'px'
        }
    );
}

FotoliaZoom.prototype.onmouseover = function(e)
{
    if (this.FotoliaZoom.hideClipTimeout) {
        window.clearTimeout(this.FotoliaZoom.hideClipTimeout);
    }

    if (this.FotoliaZoom.zoomDepth >= this.FotoliaZoom.zoomDepthMax) {
        return;
    } else if (this.loading) {
        return;
    } else {
        if (Element.visible(this.clip)) {
            return;
        }

        this.FotoliaZoom.showClip(this);
    }
}

FotoliaZoom.prototype.showClip = function(container)
{
    var clip = container.clip;

    if (typeof(container.xCord) == 'undefined' || container.xCord == 0) {
        var pos = Position.cumulativeOffset(container);
        container.xCord = pos[0];
        container.yCord = pos[1];

        var dims = Element.getDimensions(container);
        container.w = dims['width'];
        container.h = dims['height'];

        var clipDims = Element.getDimensions(clip);
        clip.w = clipDims['width'];
        clip.h = clipDims['height'];
    }

    if (container.FotoliaZoom.hideClipTimeout) {
        window.clearTimeout(container.FotoliaZoom.hideClipTimeout);
    }

    Element.show(clip);
}

FotoliaZoom.prototype.onmouseout = function(e)
{
    if (this.FotoliaZoom.hideClipTimeout) {
        window.clearTimeout(this.FotoliaZoom.hideClipTimeout);
    }

    this.FotoliaZoom.hideClipTimeout = window.setTimeout('var container = $("' + this.id + '"); container.FotoliaZoom.hideClip(container);', 100);
}

FotoliaZoom.prototype.hideClip = function(container)
{
    Element.hide(container.clip);
}

FotoliaZoom.prototype.reinit = function(container)
{
    // reinit
    if (typeof(container.originalSrc) == 'undefined') {
        return;
    }

    container.img.src = container.originalSrc;

    container.img.style.left = '0px';
    container.img.style.top = '0px';
    container.img.width = container.w;
    container.img.height = container.h;

    container.baseX = 0;
    container.baseY = 0;

    container.baseLeft = 0;
    container.baseTop = 0;

    container.FotoliaZoom.zoomDepth = 1;
    container.loading = false;
}

FotoliaZoom.prototype.onloadZoomImage = function(container)
{
    var img = container.img;

    Element.hideExt(img);

    window.setTimeout(
        function() {
            img.width = img.zoomImage.width;
            img.height = img.zoomImage.height;
            img.style.left = 0;
            img.style.top = 0;

            img.src = img.zoomImage.src;
            Element.showExt(img);
        },
        0);

    container.loading = false;

    if (container.FotoliaZoom.zoomDepth < container.FotoliaZoom.zoomDepthMax) {
        container.FotoliaZoom.showClip(container);
    }
}

FotoliaZoom.prototype.onclick = function(e)
{
    if (this.loading) {
        Event.stop(e);
        return;
    }

    if (this.FotoliaZoom.zoomDepth == 0) {
        // first call

        this.originalSrc = this.img.src;

        this.baseX = 0;
        this.baseY = 0;

        this.baseLeft = 0;
        this.baseTop = 0;

        this.FotoliaZoom.zoomDepth = 1;
    }

    if (this.onloadZoomImageTimeout) {
        window.clearTimeout(this.onloadZoomImageTimeout);
    }

    if (this.FotoliaZoom.zoomDepth >= this.FotoliaZoom.zoomDepthMax) {
        this.FotoliaZoom.reinit(this);
        this.FotoliaZoom.showClip(this);
    } else {
        var pos = Position.positionedOffset(this.img);
        var clipPos = Position.positionedOffset(this.clip);
        var dims = Element.getDimensions(this.img);

        var currentZoomRatio = Math.pow(this.FotoliaZoom.zoomRatio, this.FotoliaZoom.zoomDepth - 1);

        // we must remember where we are this.based on orginal image

        this.baseX = ((0 - this.baseLeft) + clipPos[0] + this.FotoliaZoom.bordersize + this.clip.w / 2) / currentZoomRatio;
        this.baseY = ((0 - this.baseTop) + clipPos[1] + this.FotoliaZoom.bordersize + this.clip.h / 2) / currentZoomRatio;

        this.baseLeft = (this.w / 2) - (this.baseX * this.FotoliaZoom.zoomRatio * currentZoomRatio);
        this.baseTop = (this.h / 2) - (this.baseY * this.FotoliaZoom.zoomRatio * currentZoomRatio);


        // request new image (zoom + crop) and display it
        var zoomImage = new Image();

        zoomImage.src = 'http://download.fotolia.com/Content/Zoom/' + (this.FotoliaZoom.zoomRatio * currentZoomRatio) + '/' + this.baseX + '/' + this.baseY + '/?path=' + escape(this.originalSrc);
        zoomImage.targetImg = this.img;
        zoomImage.container = this;

        this.img.zoomImage = zoomImage;

        this.loading = true;

        zoomImage.onload = function (e) {
            this.container.onloadZoomImageTimeout = window.setTimeout('var container = $("' + this.container.id + '"); container.FotoliaZoom.onloadZoomImage(container);', 10);
        };

        // and now we compute for browser zoom

        if (pos[0] == 0 && dims['width'] == this.w) {
            // no zoom for the current image
            currentZoomRatio = 1;
        }

        // dot position which will be the new center (based on current image displayed, dynamix src)
        var x = ((0 - pos[0]) + clipPos[0] + this.FotoliaZoom.bordersize + this.clip.w / 2) / currentZoomRatio;
        var y = ((0 - pos[1]) + clipPos[1] + this.FotoliaZoom.bordersize + this.clip.h / 2) / currentZoomRatio;

        // multiply dims
        var w = this.w * this.FotoliaZoom.zoomRatio * currentZoomRatio;
        var h = this.h * this.FotoliaZoom.zoomRatio * currentZoomRatio;

        // translate origin: x,y must be on the center
        var l = (this.w / 2) - (x * this.FotoliaZoom.zoomRatio * currentZoomRatio);
        var t = (this.h / 2) - (y * this.FotoliaZoom.zoomRatio * currentZoomRatio);

        // bound origins
        if (l > 0) {
            l = 0;
        } else if (l + w < this.w) {
            l = this.w - w;
        }

        if (t > 0) {
            t = 0;
        } else if (t + h < this.h) {
            t = this.h - h;
        }

        // browser zoom
        Element.setStyle(
            this.img,
            {
                position: 'absolute',
                left: Math.round(l) + 'px',
                top: Math.round(t) + 'px'
            }
        );

        // zoom with current image (browser zoom)
        this.img.width = w;
        this.img.height = h;

        this.FotoliaZoom.zoomDepth++;

        this.FotoliaZoom.hideClip(this);
    }

    Event.stop(e);
}


/*
Main object
*/
var Fotolia = {

    init: function()
    {
        // init all objects
        FotoliaZooms.init();
        FotoliaTooltip.init();
        FotoliaAjaxActions.init();
        Fotolia.initHiddenForJs();
        Fotolia.testFiltersCheckBox();
    },

    loadFile: function(file, symbolName, callback)
    {
        var head;
        var script;

        head = $$('head')[0];
        if (head) {
            script = document.createElement('script');
            script.src = file;
            script.type = 'text/javascript';
            head.appendChild(script);

            if (symbolName && callback) {
                Fotolia.watchForSymbol({
                    symbol: symbolName,
                    timeout: 3,
                    onSuccess: function(symbol) {
                        try {
                            eval(callback);
                        } catch (e) {
                        }
                    },
                    onTimeout: function(symbol) {
                    }
                });
            }
        }
    },

    watchForSymbol: function(options)
    {
        var stopAt;

        if (!options || !options.symbol || !options.onSuccess) {
            throw 'Missing required options';
        }
        options.onTimeout = options.onTimeout || Prototype.K;
        options.timeout = options.timeout || 10;
        stopAt = (new Date()).getTime() + (options.timeout * 1000);
        new PeriodicalExecuter(function(pe) {
            if (typeof window[options.symbol] != 'undefined') {
                options.onSuccess(options.symbol);
                pe.stop();
            } else if ((new Date()).getTime() > stopAt) {
                options.onTimeout(options.symbol);
                pe.stop();
            }
        }, 0.25);
    },

    testFiltersCheckBox: function() {
        var c = document.getElementsByTagName('input');
        for (var i = 0, l = c.length; i < l; i++) {
            switch (c[i].id) {
                case 'filter:content_type:photo':
                    Event.observe(c[i], 'click', Fotolia.filtersEventBox);
                    break;
                case 'filter:content_type:illustration':
                    Event.observe(c[i], 'click', Fotolia.filtersEventBox);
                    break;
                case 'filter:content_type:vector':
                    Event.observe(c[i], 'click', Fotolia.filtersEventBox);
                    break;
                case 'filter:content_type:video':
                    Event.observe(c[i], 'click', Fotolia.filtersEventBox);
                    break;
                case 'filter:content_type:all':
                    Event.observe(c[i], 'click', Fotolia.filtersEventBox);
                    break;
            }
        }
    },

    filtersEventBox: function(e) {
        var elm = Event.element(e);

        var all_elm = $('filter:content_type:all');

        if (all_elm) {
            switch (elm.id) {
                case 'filter:content_type:photo':
                    if (elm.checked) {
                        all_elm.checked = false;
                    }
                    break;
                case 'filter:content_type:illustration':
                    if (elm.checked) {
                        all_elm.checked = false;
                    }
                    break;
                case 'filter:content_type:vector':
                    if (elm.checked) {
                        all_elm.checked = false;
                    }
                    break;
                case 'filter:content_type:video':
                    if (elm.checked) {
                        all_elm.checked = false;
                    }
                    break;
                case 'filter:content_type:all':
                    if (elm.checked) {
                        var photo_elm = $('filter:content_type:photo');
                        var illustration_elm = $('filter:content_type:illustration');
                        var vector_elm = $('filter:content_type:vector');
                        var video_elm = $('filter:content_type:video');

                        if (photo_elm) {
                            photo_elm.checked = false;
                        }
                        if (illustration_elm) {
                            illustration_elm.checked = false;
                        }
                        if (vector_elm) {
                            vector_elm.checked = false;
                        }
                        if (video_elm) {
                            video_elm.checked = false;
                        }
                    }
                    break;
            }
        }
    },

    initHiddenForJs: function() {
        var c = document.getElementsByTagName('input');
        for (var i = 0, l = c.length; i < l; i++) {
            if (c[i].className == 'js_hidden') {
                Element.hideExt(c[i]);
            }
        }
    },

    debug: function(e)
    {
        alert('Error:');
        alert(e);
    },

    changeMainClassName: function (className)
    {
        var b = document.getElementsByTagName('body')[0];
        b.className = className;
    },

    affiliationToggleAll: function(selected)
    {
        root = $('affiliation');
        var inputs = root.getElementsByTagName('input');
        for (i = 0; i < inputs.length; i++) {
            if (inputs[i].type == 'checkbox') {
                inputs[i].checked = selected;
            }
        }
    },

    goToPage: function(n, limit, nb_contents, url)
    {
        if (n != parseInt(n)) {
            return;
        }

        if (n < 1) {
            n = 1;
        } else if (n > Math.ceil(nb_contents / limit)) {
            n = Math.ceil(nb_contents / limit);
        }

        window.location.href = url + ((n - 1) * limit);
    }
}

Event.onDOMReady(function() {
    Fotolia.init();
});

FotoliaDownloadContent = {

    init: function()
    {
        if(!$('shoppingcart_download')) {
            return false;
        }

        // set licenses_possibilities
        FotoliaShoppingCart.setLicensePossibilities();

        // set event on can and cannot link
        FotoliaShoppingCart.initLicensePossibilitiesBox();

        // retrieve contents selected licenses
        FotoliaDownloadContent.retrieveContentsSelectedLicenses();
    },

    retrieveContentsSelectedLicenses: function() {
        var contents_licenses = new Array();

        var c = document.getElementsByTagName('input');
        for (var i = 0, l =  c.length; i < l; i++) {
            if (c[i].id && c[i].id.match(/^contents_licenses:[0-9]+$/) && c[i].type == 'hidden') {

                var matches = /^contents_licenses:([0-9]+)$/.exec(c[i].id);
                content_id = matches[1];
                license_abbr = c[i].value;

                contents_licenses[content_id] = license_abbr;
            }
        }

        FotoliaShoppingCart.contents_licenses = contents_licenses;
    },

    setDownloadButtonsActions: function()
    {
        switch(this.id) {
            case '':
                alert(_('Error'));
                break;

            default:
                alert('No action for : '  + this.id);
        }

        return false;
    }
}

Event.onDOMReady(function() {
    FotoliaDownloadContent.init();
});

FotoliaShoppingCart = {

    xCord: 0,                // @Number: x pixel value of current cursor position
    yCord: 0,                // @Number: y pixel value of current cursor position
    ajaxMode: 1,
    currentTooltip: Object,

    licenses_possibilities: new Array(),
    contents_licenses: new Array(),

    init: function()
    {
        if(!$('totalPrice')) {
            return false;
        }

        // set licenses_possibilities
        FotoliaShoppingCart.setLicensePossibilities();

        // retrieve contents selected licenses
        FotoliaShoppingCart.retrieveContentsSelectedLicenses();

        // set event on can and cannot link
        FotoliaShoppingCart.initLicensePossibilitiesBox();

        FotoliaShoppingCart.initCheckoutButtons();

        FotoliaShoppingCart.initLicenseAcceptAll();

        FotoliaShoppingCart.initConfirmationMessages();
    },

    showConfirmMessage: function(e, message) {
        if (!confirm(message)) {
            Event.stop(e);
        }
    },

    initConfirmationMessages: function() {
        remove_content_link_all_id = $('remove_content_link_all');
        if (remove_content_link_all_id) {
            remove_content_link_all_id.observe('click',  FotoliaShoppingCart.showConfirmMessage.bindAsEventListener(remove_content_link_all_id, _('Do you really want to remove all files from Shopping Cart?')));
        }

        transfer_to_lightbox_id = $('transfer_to_lightbox');
           if (transfer_to_lightbox_id) {
               transfer_to_lightbox_id.observe('click',  FotoliaShoppingCart.showConfirmMessage.bindAsEventListener(transfer_to_lightbox_id, _('Do you really want to transfer all files to Lightbox?')));
           }
    },

    retrieveContentsSelectedLicenses: function() {
        var contents_licenses = new Array();

        var c = document.getElementsByTagName('input');
        for (var i = 0, l =  c.length; i < l; i++) {
            if(c[i].id && c[i].id.match(/^(.+):[0-9]+:(.+)$/) && c[i].type == 'radio' && c[i].checked == true) {
                var matches = /:([0-9]+):(.+)$/.exec(c[i].id);
                content_id = matches[1];
                license_abbr = matches[2];

                contents_licenses[content_id] = license_abbr;
            }
        }

        FotoliaShoppingCart.contents_licenses = contents_licenses;
    },

    setLicensePossibilities: function()
    {
        var licenses_possibilities = new Array();
        licenses_possibilities["XS"] = new Array();
        licenses_possibilities["XS"]["CAN"] = new Array();
        licenses_possibilities["XS"]["CAN"][0] = _("Use the Work in all print  and electronic or online  materials, and web pages");
        licenses_possibilities["XS"]["CAN"][1] = _("Modify image or use in derivative works");
        licenses_possibilities["XS"]["CAN"][2] = _("Make back up copies");
        licenses_possibilities["XS"]["CANNOT"] = new Array();
        licenses_possibilities["XS"]["CANNOT"][0] = _("Resell original image");
        licenses_possibilities["XS"]["CANNOT"][1] = _("Use image in any way that violates local or federal laws");
        licenses_possibilities["XS"]["CANNOT"][2] = _("Distribute copies of image to friends, family, or other organizations");

        licenses_possibilities["V_S"] = new Array();
        licenses_possibilities["V_S"]["CAN"] = new Array();
        licenses_possibilities["V_S"]["CAN"][0] = _("Use the Work in all print  and electronic or online  materials, and web pages");
        licenses_possibilities["V_S"]["CAN"][1] = _("Modify image or use in derivative works");
        licenses_possibilities["V_S"]["CAN"][2] = _("Make back up copies");
        licenses_possibilities["V_S"]["CANNOT"] = new Array();
        licenses_possibilities["V_S"]["CANNOT"][0] = _("Resell original image");
        licenses_possibilities["V_S"]["CANNOT"][1] = _("Use image in any way that violates local or federal laws");
        licenses_possibilities["V_S"]["CANNOT"][2] = _("Distribute copies of image to friends, family, or other organizations");

        licenses_possibilities["X"] = new Array();
        licenses_possibilities["X"]["CAN"] = new Array();
        licenses_possibilities["X"]["CAN"][0] = _("Modify the image or integrate it into derived works");
        licenses_possibilities["X"]["CAN"][1] = _("Use, reproduce, or display images in goods and services intended for resale and distribution");
        licenses_possibilities["X"]["CAN"][2] = _("Make a backup copy of the image");
        licenses_possibilities["X"]["CANNOT"] = new Array();
        licenses_possibilities["X"]["CANNOT"][0] = _("Resell original image");
        licenses_possibilities["X"]["CANNOT"][1] = _("Use image in any way that violates local or federal laws");
        licenses_possibilities["V_X"] = new Array();
        licenses_possibilities["V_X"]["CAN"] = new Array();
        licenses_possibilities["V_X"]["CAN"][0] = _("Modify the image or integrate it into derived works");
        licenses_possibilities["V_X"]["CAN"][1] = _("Use, reproduce, or display images in goods and services intended for resale and distribution");
        licenses_possibilities["V_X"]["CAN"][2] = _("Make a backup copy of the image");
        licenses_possibilities["V_X"]["CANNOT"] = new Array();
        licenses_possibilities["V_X"]["CANNOT"][0] = _("Resell original image");
        licenses_possibilities["V_X"]["CANNOT"][1] = _("Use image in any way that violates local or federal laws");

        licenses_possibilities["E"] = new Array();
        licenses_possibilities["E"]["CAN"] = new Array();
        licenses_possibilities["E"]["CAN"][0] = _("Exclusively lock out all future sales of this image");
        licenses_possibilities["E"]["CAN"][1] = _("Use the Work in all print  and electronic or online  materials, and web pages");
        licenses_possibilities["E"]["CAN"][2] = _("Use, reproduce, or display images in goods and services intended for resale and distribution");
        licenses_possibilities["E"]["CAN"][3] = _("Make back up copies");
        licenses_possibilities["E"]["CAN"][4] = _("Modify image or use in derivative works");
        licenses_possibilities["E"]["CANNOT"] = new Array();
        licenses_possibilities["E"]["CANNOT"][0] = _("Resell original image");
        licenses_possibilities["E"]["CANNOT"][1] = _("Use image in any way that violates local or federal laws");

        licenses_possibilities["V"] = new Array();
        licenses_possibilities["V"]["CAN"] = new Array();
        licenses_possibilities["V"]["CAN"][0] = _("Use the Work in all print  and electronic or online  materials, and web pages");
        licenses_possibilities["V"]["CAN"][1] = _("Modify image or use in derivative works");
        licenses_possibilities["V"]["CAN"][2] = _("Make back up copies");
        licenses_possibilities["V"]["CANNOT"] = new Array();
        licenses_possibilities["V"]["CANNOT"][0] = _("Resell original image");
        licenses_possibilities["V"]["CANNOT"][1] = _("Use image in any way that violates local or federal laws");
        licenses_possibilities["V"]["CANNOT"][2] = _("Distribute copies of image to friends, family, or other organizations");
        licenses_possibilities["XV"] = new Array();
        licenses_possibilities["XV"]["CAN"] = new Array();
        licenses_possibilities["XV"]["CAN"][0] = _("Modify the image or integrate it into derived works");
        licenses_possibilities["XV"]["CAN"][1] = _("Use, reproduce, or display images in goods and services intended for resale and distribution");
        licenses_possibilities["XV"]["CAN"][2] = _("Make a backup copy of the image");
        licenses_possibilities["XV"]["CANNOT"] = new Array();
        licenses_possibilities["XV"]["CANNOT"][0] = _("Resell original image");
        licenses_possibilities["XV"]["CANNOT"][1] = _("Use image in any way that violates local or federal laws");

        FotoliaShoppingCart.licenses_possibilities = licenses_possibilities;
    },

    initLicensePossibilitiesBox: function() {

        // assign cannot action
        var c = document.getElementsByTagName('a');
        for (var i = 0, l = c.length; i < l; i++) {
            if (c[i].id && (c[i].id.match(/^can_do:[0-9]+$/) || c[i].id.match(/^cannot_do:[0-9]+$/))) {
                addEvent(c[i], 'mouseover', this.setLicensePossibilitiesBoxAction);
                addEvent(c[i], 'mousemove', this.tipMove);
                addEvent(c[i], 'mouseout', this.tipOut);
            }
        }
    },

    // retrieve index of ID
    retrieveIndex: function(e) {
        var matches = /:([0-9]+)$/.exec(e.id);
        return matches[1];
    },

    setLicensePossibilitiesBoxAction: function() {
        // get current license
        var standard_license_abbr = new Array('XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL');
        var standard_video_license_abbr = new Array('V_S', 'V_M', 'V_PAL', 'V_NTSC', 'V_HD720', 'V_HD1080');
        var content_id = FotoliaShoppingCart.retrieveIndex(this);
        var selected_license_abbr = FotoliaShoppingCart.contents_licenses[content_id];

        if (selected_license_abbr.indexOf('Subscription_') != -1) {
            selected_license_abbr = selected_license_abbr.replace('Subscription_', '');
        }

        // detect action
        var type;
        if (this.id.match(/^can_do:[0-9]+$/)) {
            type = 'can';
        } else if (this.id.match(/^cannot_do:[0-9]+$/)) {
            type = 'cannot';
        } else if (this.id.match(/^see_contract:[0-9]+$/)) {
            type = 'contract';
        }

        var test = standard_license_abbr.indexOf(selected_license_abbr);
        if (test != -1) {
            selected_license_abbr = 'XS';
        } else {
            var test = standard_video_license_abbr.indexOf(selected_license_abbr);
            if (test != -1) {
                selected_license_abbr = 'V_S';
            }
        }

        switch (type) {
            case 'can':
                FotoliaShoppingCart.displaylicensetooltip('CAN', selected_license_abbr);
                break;

            case 'cannot':
                FotoliaShoppingCart.displaylicensetooltip('CANNOT', selected_license_abbr);
                break;

            case 'contract':
                break;

            default:

        }
    },

    // display a tooltip and create div if not exist
    displaylicensetooltip: function(type, license_abbr) {

        // detect standart license
        var tooltip_id = 'FotoliaLicenseTooltip_' + license_abbr + '_' +  type;
        var licenses_possibilities= FotoliaShoppingCart.licenses_possibilities[license_abbr][type];

        // test if tooltip exist
        if (!$(tooltip_id)) {

            // extract value
            var tooltip_value = '<ul>';
            for (var i = 0, l = licenses_possibilities.length; i < l; i++) {
                tooltip_value += '<li>' + licenses_possibilities[i] + '</li>';
            }
            tooltip_value += '</ul>';

            // create object
            var new_tooltip = new Object;
            new_tooltip = document.createElement('div');
            Element.update( new_tooltip, tooltip_value);
            new_tooltip.id = tooltip_id;

            document.getElementsByTagName('body')[0].appendChild(new_tooltip);
            new_tooltip.style.top = '0';
            new_tooltip.className = 'license-tooltip static-model';
            new_tooltip.style.position = 'absolute';
            FotoliaShoppingCart.currentTooltip = new_tooltip;
        } else {
            var c = document.getElementById(tooltip_id);
            FotoliaShoppingCart.currentTooltip = c;
        }

        FotoliaShoppingCart.currentTooltip.style.visibility = 'visible';

    },

    // update x and y coord from event position
    updateXY: function(e) {
        if (document.captureEvents) {
            FotoliaShoppingCart.xCord = e.pageX;
            FotoliaShoppingCart.yCord = e.pageY;
        } else if ( window.event.clientX ) {
            FotoliaShoppingCart.xCord = window.event.clientX + document.documentElement.scrollLeft;
            FotoliaShoppingCart.yCord = window.event.clientY + document.documentElement.scrollTop;
        }
    },

    // move the tooltip
    tipMove: function(e) {
        if (e) {
            FotoliaShoppingCart.updateXY(e);
        }

        var scrX = Number(FotoliaShoppingCart.xCord);
        var scrY = Number(FotoliaShoppingCart.yCord);
        var tp = parseInt(scrY + 15);
        var lt = parseInt(scrX);

        var oWidth = 200;

        minlt = oWidth / 2;
        maxlt = parseInt(document.documentElement.clientWidth) + parseInt(document.documentElement.scrollLeft) - oWidth / 2;

        lt = Math.min(maxlt, lt);
        lt = Math.max(minlt, lt);

        tlt = lt - oWidth / 2;

        if (parseInt(document.documentElement.clientHeight + document.documentElement.scrollTop) < parseInt(FotoliaShoppingCart.currentTooltip.offsetHeight + tp)) {
            ttp = tp - parseInt(FotoliaShoppingCart.currentTooltip.offsetHeight) - 25;
        } else {
            ttp = tp;
        }

        if (FotoliaShoppingCart.currentTooltip.style) {
            FotoliaShoppingCart.currentTooltip.style.left = tlt + 'px';
            FotoliaShoppingCart.currentTooltip.style.top = ttp + 'px';
        }
    },

    // hide the tooltip when the mouse cursor is going out of the link area
    tipOut: function(e) {
        FotoliaShoppingCart.currentTooltip.style.visibility = 'hidden';
    },

    // update shopping cart total price
    updateTotalPrice: function(total_price_string)
    {
        $('totalPrice').firstChild.nodeValue = total_price_string;
    },

    // update shopping cart total price
    updateNbItem: function(nbItem)
    {
        $('nbItem').firstChild.nodeValue = nbItem;
    },

    // update shopping cart remaining credits
    updateRemainingCredits: function(remaining_credits, remaining_credits_string)
    {
        remaining_credits_item = $('remaining_credits');
        remaining_credits_item.update(remaining_credits_string);

        if (remaining_credits < 0) {
            Element.showInline($('buy_credit_link'));
            remaining_credits_item.addClassName('error_msg');
        } else {
            Element.hideInline($('buy_credit_link'));
            remaining_credits_item.removeClassName('error_msg');
        }
    },

    updateShoppingcartNbContents: function(nbContents)
    {
        $('shoppingcart:nbcontents').update(nbContents);
    },

    // remove content in shopping cart and make somes actions in the action from Shopping cart
    removeShoppingcartContents: function(content_id)
    {
        if($('totalPrice')) {

            Element.hideExt($('selected_license_infos:' + content_id));
            Element.hideExt($('no_selected_license_infos:' + content_id));
            Element.showExt($('remove_from_shopping_cart:' + content_id));

            // update content license choise
            var c = $('licenses_choice:'+ content_id).getElementsByTagName('tr');
            for (var i = 0, l = c.length; i < l; i++) {
                var license_line = c[i];
                license_line.className = null;
            }

            var c = $('licenses_choice:'+ content_id).getElementsByTagName('input');
            for (var i = 0, l = c.length; i < l; i++) {
                var license_line = c[i];
                license_line.checked = false;
            }

            Element.hideExt($('remove_content_link:'+ content_id));

            if ($('no_license:'+ content_id)) {
                $('no_license:'+ content_id).style.visibility = 'hidden';
                //Element.hideExt($('no_license:'+ content_id));
            }
        }
    },

    afterRemoveShoppingcartContents: function(msg)
    {
        Element.hideInline($('shoppingcartinfos'));
        if ($('shoppingcarthowtobox')) {
            $('shoppingcarthowtobox').setStyle({width: '100%'});
        }
        var message = document.createElement('p');
        message.appendChild(document.createTextNode(msg));
        $('content').insertBefore(message, $('shoppingcarthowtobox').parentNode);
    },

    updateShoppingcartData: function(nb_contents, total_price_string, remaining_credits, remaining_credits_string, nb_valid_contents)
    {
        if (typeof(nb_valid_contents) == 'undefined') {
            nb_valid_contents = nb_contents;
        }

        // update shopping cart prices
        if($('totalPrice')) {
            FotoliaShoppingCart.updateNbItem(nb_valid_contents);
            FotoliaShoppingCart.updateTotalPrice(total_price_string);
            FotoliaShoppingCart.updateRemainingCredits(remaining_credits, remaining_credits_string);
        }

        if($('shoppingcart:nbcontents')) {
            FotoliaShoppingCart.updateShoppingcartNbContents(nb_contents);
        }
    },

    updateHref: function(id, href)
    {
        item = $(id);

        if (item) {
            item.href = href;
        }
    },

    // update content in shopping cart and make somes actions in the action from Shopping cart
    chooseLicenseInShoppingcart: function(content_id, license_abbr, license_name, license_new_real_price)
    {
        if ($('totalPrice')) {
            // update contents licenses array
            FotoliaShoppingCart.contents_licenses[content_id] = license_abbr;

            // update content licence infos
            Element.showExt($('selected_license_infos:' + content_id));
            Element.hideExt($('no_selected_license_infos:' + content_id));
            Element.hideExt($('remove_from_shopping_cart:' + content_id));

            Element.showExt($('remove_license:' + content_id));

            // update no content license
            if ($('no_license:'+ content_id)) {
                //Element.hideExt($('no_license:'+ content_id));
                $('no_license:'+ content_id).style.visibility = 'hidden';
            }

            // reset remove shoppingcart button
            var remove_content_link = $('remove_content_link:'+ content_id);
            Element.showExt(remove_content_link);
            if (remove_content_link.old_onclick) {
                remove_content_link.reEnabledOnclickTimeout();
                remove_content_link.className = null;
            }

            // update content license choise
            var c = $('licenses_choice:'+ content_id).getElementsByTagName('tr');
            for (var i = 0, l = c.length; i < l; i++) {
                var license_line = c[i];
                if (license_line.id == 'licence_line:' + content_id + ':' + license_abbr) {
                    license_line.className = 'selected_license';
                } else {
                    license_line.className = null;
                }
            }

            // update license properies
            selected_license_price = $('selected_license_price:' + content_id);
            selected_license_name = $('selected_license_name:' + content_id);

            Element.update(selected_license_price, license_new_real_price);
            Element.update(selected_license_name, translateLicense(license_name));
        }
    },

    initCheckoutButtons: function()
    {
        // set simple action
        var action_buttons = new Array(
            'checkout_button'
        );

        for (var i = 0, l =  action_buttons.length; i < l; i++) {
            if ($(action_buttons[i])) {
                button = $(action_buttons[i]);
                button.onclick = FotoliaShoppingCart.setButtonsActions;
            }
        }

        // set ajax action on tr and radio
        FotoliaShoppingCart.initTrLicense();
        FotoliaShoppingCart.initRadioLicense();
    },

    initTrLicense: function()
    {
        // set color change on tr
        var tr_licenses = document.getElementsByTagName('tr');
        var license_abbr = new Array();
        var content_id = new Array();

        for (var i = 0, l = tr_licenses.length; i < l; i++) {
            if (tr_licenses[i].id && tr_licenses[i].id.match(/^licence_line:[0-9]+:(.*)+$/)) {
                tr_licenses[i].type = 'tr';
                tr_licenses[i].onclick = FotoliaShoppingCart.setLicenseToContent;
            }
        }
    },

    initRadioLicense: function()
    {
        // add events to Radio input
        var radio_licenses = document.getElementsByTagName('input');

        for (var i = 0, l = radio_licenses.length; i < l; i++) {
            if (radio_licenses[i].type != 'radio') {
                continue;
            }

            if (radio_licenses[i].id && radio_licenses[i].id.match(/^license:[0-9]+$/)) {
                radio_licenses[i].onclick = FotoliaShoppingCart.setLicenseToContent;
            }
        }
    },

    initLicenseAcceptAll: function()
    {
        if ($('license_accept_all')) {
            $('license_accept_all').onchange = FotoliaShoppingCart.setLicenseToAllContents;
        }
    },

    setLicenseToAllContents: function(e)
    {
        var radio_licenses = document.getElementsByTagName('input');
        var regexp = new RegExp('^license:[0-9]+:' + this.value + '$');

        for (var i = 0, l = radio_licenses.length; i < l; i++) {
            if (radio_licenses[i].type != 'radio') {
                continue;
            }
            if (radio_licenses[i].id && radio_licenses[i].id.match(regexp)) {
                alert (radio_licenses[i].id);
                $(radio_licenses[i].id).click();
            }
        }

    },

    setLicenseToContent: function(e)
    {
        // @todo tagname...
        switch (this.type) {
            case 'tr':
                var matches = /^licence_line:([0-9]+):(.+)$/.exec(this.id);
                var content_id = matches[1];
                var license_abbr = matches[2];

                //check radio
                radio_license = $('license:' +  content_id + ':' + license_abbr);
                $('license:' +  content_id + ':' + license_abbr).checked = true;

                break;

            case 'radio':
                var regexp = new RegExp('^license:([0-9]+)', 'g');
                var results = regexp.exec(current[j].name);
                var content_id = results[1];
                var license_abbr = this.value;
                break;

            default:
                break;

        }

        url = '/Ajax/ChooseLicenseInShoppingCart/?content_id=' + content_id + '&license=' + license_abbr;

        var pars = '';
        var myAjax = new Ajax.Request();
        myAjax.setOptions(
            {
                method: 'get',
                parameters: pars,
                onComplete: FotoliaAjaxActions.XHRResponseTextCallback
            }
        );

        // reference to source
        myAjax.sourceObject = this;

        myAjax.request(url);

        return true;
    },

    setButtonsActions: function()
    {
        var checkbox_contract_accept = $('contract_accept');

        switch (this.id) {
            case 'checkout_button':
                if (checkbox_contract_accept.checked) {
                    if (FotoliaShoppingCart.ajaxMode) {
                        myLightWindow.activateWindow({
                            href: '/Ajax/ShoppingCart/Checkout',
                            type: 'page'
                        });
                        return false;
                    } else {
                        return true;
                    }
                }

                alert(_('Please check the box to accept contract and continue'));
                break;

            default:
                //alert('No action for : '  + this.id);
        }

        return false;
    },

    unselectLicense: function(content_id)
    {
        $A(document.getElementsByName('license[' + content_id + ']')).each(function(item){item.checked = false;});
        $('selected_license_infos:' + content_id).hide();
        $('remove_license:' + content_id).hide();
        $('no_selected_license_infos:' + content_id).className = null;
        $('no_selected_license_infos:' + content_id).show();

        if ($('no_license:'+ content_id)) {
            $('no_license:'+ content_id).style.visibility = "visible";
        }
    }
}

Event.onDOMReady(function() {
    FotoliaShoppingCart.init();
});

var FotoliaTickets = {
    //ini lightbox action button
    initAction: function() {
        if (!$('content_form')) {
            return false;
        }

        var action_buttons = new Array(
            'inverseMsgSelect'
        );

        for (var i = 0, l =  action_buttons.length; i < l; i++) {
            if ($(action_buttons[i])) {
                button = $(action_buttons[i]);
                if (button.type == 'select-one') {
                    button.onchange = FotoliaTickets.action;
                } else {
                    button.onclick = FotoliaTickets.action;
                }
            }
        }

        FotoliaTickets.initActionToCheckBox();
    },

    nbAvailableCheckBox: 0,
    nbCheckedCheckBox: 0,

    //action for contents checkboxes
    initActionToCheckBox: function() {
        var c = document.getElementsByTagName('input');
        var return_value = '';

        var nbAvailableCheckBox = 0;
        for (var i = 0, l = c.length; i < l; i++) {
            if (c[i].type == 'checkbox' && c[i].id && c[i].id.match(/^msg_ids:[0-9]+$/)) {
                c[i].onchange = function() {
                    if (this.checked == true) {
                        FotoliaTickets.nbCheckedCheckBox++;
                    } else {
                        FotoliaTickets.nbCheckedCheckBox--;
                    }

                    if (FotoliaTickets.nbAvailableCheckBox == FotoliaTickets.nbCheckedCheckBox) {
                        $('inverseMsgSelect').checked = true;
                    } else {
                        $('inverseMsgSelect').checked = false;
                    }
                }
            }
        }

        FotoliaTickets.nbCheckedCheckBox = 0;
        FotoliaTickets.nbAvailableCheckBox = nbAvailableCheckBox;
    },

    //set action for evenement
    action: function() {
        switch(this.id) {
            case 'inverseMsgSelect':
                FotoliaTickets.actionForInverseMsgSelect(this.checked);
                break;

            default:
        }
    },

    actionForInverseMsgSelect: function(v) {
        var c = document.getElementsByTagName('input');

        for (var i = 0, l = c.length; i < l; i++) {
            if (c[i].type == 'checkbox' && c[i].id && c[i].id.match(/^msg_ids:[0-9]+$/)) {
                c[i].checked = v;
            }
        }

        return true;
    }
}

var FotoliaDownloadFolder = {
    initAction: function() {

        if (!$('download_project_form')) {
            return false;
        }

        var action_buttons = new Array(
            'add_new_project',
            'add_project_cancel',
            'edit_project',
            'edit_project_cancel',
            'inverseSelected',
            'movetofolder',
            'movetofolder_button',
            'removefromfolder'
        );

        for (var i = 0, l =  action_buttons.length; i < l; i++) {
            if($(action_buttons[i])) {
                button = $(action_buttons[i]);
                button.onclick = FotoliaDownloadFolder.setAction;
            }
        }
    },

    //action for contents checkboxes
    setActionToCheckBox: function(action) {

        var c = document.getElementsByTagName('input');
        var return_value = '';

        for (var i = 0, l = c.length; i < l; i++) {
            if (c[i].type == 'checkbox' && c[i].id && c[i].id.match(/^content_download_id32s:[a-zA-Z0-9]+$/)) {

                /*var parent_status = c[i].parentNode.parentNode.status;
                if (parent_status == 'next' || parent_status == 'previous') {
                    continue;
                }*/

                switch(action) {
                    case 'check_all':
                    c[i].checked = true;
                    return_value[i] = c[i];
                    break;

                    case 'uncheck_all':
                    c[i].checked = false;
                    break;
                }
            }
        }

        return return_value;
    },

    setAction: function() {
        switch(this.id) {
            //open add project form
            case 'add_new_project':
                var add_project_form = $('add_project_form');
                var add_project_button = $('add_project_button');

                Element.showExt(add_project_form);
                return false;

                break;

            //close add project form
            case 'add_project_cancel':
                var add_project_form = $('add_project_form');
                var add_project_button = $('add_project_button');

                Element.hideExt(add_project_form);
                return false;

                break;

            //open modify project form
            case 'edit_project':
                var edit_project_form = $('edit_project_form');
                Element.showExt(edit_project_form);
                return false;

                break;

            //close modify project form
            case 'edit_project_cancel':
                var edit_project_form = $('edit_project_form');
                Element.hideExt(edit_project_form);
                return false;

                break;

            case 'inverseSelected':
                if (this.checked == true) {
                    FotoliaDownloadFolder.setActionToCheckBox('check_all');
                } else {
                    FotoliaDownloadFolder.setActionToCheckBox('uncheck_all');
                }

                break;

            //add to selected folder all checked contents
            case 'movetofolder':
            case 'movetofolder_button':
                if ($('movetofolder').value != 'none') {
                    var pars = Form.serialize($('download_project_form'));
                    var myAjax = new Ajax.Request(
                        '/Ajax/LinkToDownloadFolder',
                        {
                            method: 'post',
                            parameters: pars,
                            onLoading: FotoliaAjaxActions.hrefLoading,
                            onComplete: FotoliaAjaxActions.XHRResponseTextCallback
                        }
                    );

                    $('movetofolder').value = 'none';
                }

                return false;

                break;

            //remove all checked contents from current folder
            case 'removefromfolder':
                var pars = Form.serialize($('download_project_form'));
                var url = '/Ajax/RemoveLinkFromDownloadFolder';
                var myAjax = new Ajax.Request(
                    url,
                    {
                        method: 'post',
                        parameters: pars,
                        onLoading: FotoliaAjaxActions.hrefLoading,
                        onComplete: FotoliaAjaxActions.XHRResponseTextCallback
                    }
                );

                return false;

                break;

            default:
        }
    }
}

var FotoliaReleaseFolder = {
    initAction: function() {

        if (!$('release_project_form')) {
            return false;
        }

        var action_buttons = new Array(
            'add_new_folder',
            'add_folder_cancel',
            'edit_folder',
            'edit_folder_cancel',
            'inverseSelected',
            'movetofolder',
            'movetofolder_button',
            'removefromfolder'
        );

        for (var i = 0, l =  action_buttons.length; i < l; i++) {
            if ($(action_buttons[i])) {
                button = $(action_buttons[i]);
                //addEvent(button, 'click', FotoliaReleaseFolder.setAction);
                button.onclick = FotoliaReleaseFolder.setAction;
            }
        }
    },

    //action for contents checkboxes
    setActionToCheckBox: function(action) {

        var c = document.getElementsByTagName('input');
        var return_value = '';

        for (var i = 0, l = c.length; i < l; i++) {
            if (c[i].type == 'checkbox' && c[i].id && c[i].id.match(/^release_id32s:[a-zA-Z0-9]+$/)) {
                switch(action) {
                    case 'check_all':
                    c[i].checked = true;
                    return_value[i] = c[i];
                    break;

                    case 'uncheck_all':
                    c[i].checked = false;
                    break;
                }
            }
        }

        return return_value;
    },

    setAction: function() {
        switch(this.id) {
            // open add project form
            case 'add_new_folder':
                var add_folder_form = $('add_folder_form');

                Element.showExt(add_folder_form);
                return false;

                break;

            // close add project form
            case 'add_folder_cancel':
                var add_folder_form = $('add_folder_form');

                Element.hideExt(add_folder_form);
                return false;

                break;

            // open modify folder name form
            case 'edit_folder':
                var edit_folder_form = $('edit_folder_form');
                Element.showExt(edit_folder_form);
                return false;

                break;

            // close modify folder name form
            case 'edit_folder_cancel':
                var edit_folder_form = $('edit_folder_form');
                Element.hideExt(edit_folder_form);
                return false;

                break;

            case 'inverseSelected':
                if (this.checked == true) {
                    FotoliaReleaseFolder.setActionToCheckBox('check_all');
                } else {
                    FotoliaReleaseFolder.setActionToCheckBox('uncheck_all');
                }

                break;

            // add to selected folder all checked contents
            case 'movetofolder':
            case 'movetofolder_button':
                if ($('movetofolder').value != 'none') {
                    var pars = Form.serialize($('release_project_form'));
                    var myAjax = new Ajax.Request(
                        '/Ajax/LinkToReleaseFolder',
                        {
                            method: 'post',
                            parameters: pars,
                            onLoading: FotoliaAjaxActions.hrefLoading,
                            onComplete: FotoliaAjaxActions.XHRResponseTextCallback
                        }
                    );

                    $('movetofolder').value = 'none';
                }

                return false;

                break;

            // remove all checked releases from current folder
            case 'removefromfolder':
                var pars = Form.serialize($('release_project_form'));
                var url = '/Ajax/RemoveLinkFromReleaseFolder';
                var myAjax = new Ajax.Request(
                    url,
                    {
                        method: 'post',
                        parameters: pars,
                        onLoading: FotoliaAjaxActions.hrefLoading,
                        onComplete: FotoliaAjaxActions.XHRResponseTextCallback
                    }
                );

                return false;

                break;

            default:
        }
    }
}

var FotoliaLightbox = {
    usedForm: null,

    updateLightboxNbContents: function(nbContents)
    {
        $('current_lightbox:nbcontents').firstChild.nodeValue = nbContents;
    },

    updateModerationLightboxNbContents: function(nbContents)
    {
        $('moderation_lightbox:nbcontents').firstChild.nodeValue = nbContents;
    },

    //ini lightbox action button
    initAction: function() {

        if($('lightbox_form')){
            FotoliaLightbox.usedForm = $('lightbox_form');

            $$('#lightbox_form a').each(function(el)
                {
                    if (el.readAttribute('id') == 'remove_gallery') {
                        el.onclick = function() {
                            if (confirm(_('Are you sure?'))) {
                                return true;
                            }
                            return false;
                        };
                    }
                }
            )
        }

        if($('content_form')) {
             FotoliaLightbox.usedForm = $('content_form');
        }

        if (!$('lightbox_form') && !$('content_form')) {
            return false;
        }

        var action_buttons = new Array(
            'add_new_gallery',
            'add_gallery_cancel',
            'edit_gallery',
            'edit_gallery_cancel',
            'removefromlightbox',
            'addtoshoppingcarts',
            'movetolightbox',
            'movetolightbox_button',
            'inverseSelected'
        );

        for (var i = 0, l =  action_buttons.length; i < l; i++) {
            if($(action_buttons[i])) {
                button = $(action_buttons[i]);
                if(button.type == 'select-one') {
                    button.onchange = FotoliaLightbox.setAction;
                } else {
                    button.onclick = FotoliaLightbox.setAction;
                }
            }
        }

        if($('lightbox_contents')) {
            FotoliaLightbox.getLightboxTableNodeIndex('lightbox_contents');
            FotoliaLightbox.initActionToCheckBox();
        }

    },

    //action for contents checkboxes
    setActionToCheckBox: function(action) {

        var c = document.getElementsByTagName('input');
        var return_value = '';

        for (var i = 0, l = c.length; i < l; i++) {
            if (c[i].type == 'checkbox' && c[i].id && c[i].id.match(/^content_ids:[0-9]+$/)) {

                var parent_status = c[i].parentNode.parentNode.status;
                if (parent_status == 'next' || parent_status == 'previous') {
                    continue;
                }

                switch(action) {
                    case 'check_all':
                    FotoliaLightbox.nbCheckedCheckBox = FotoliaLightbox.nbAvailableCheckBox;
                    c[i].checked = true;
                    return_value[i] = c[i];
                    break;

                    case 'uncheck_all':
                    FotoliaLightbox.nbCheckedCheckBox = 0;
                    c[i].checked = false;
                    break;
                }
            }
        }

        return return_value;
    },

    nbAvailableCheckBox: 0,
    nbCheckedCheckBox: 0,

    //action for contents checkboxes
    initActionToCheckBox: function() {
        var c = document.getElementsByTagName('input');
        var return_value = '';

        var nbAvailableCheckBox = 0;
        for (var i = 0, l = c.length; i < l; i++) {
            if (c[i].type == 'checkbox' && c[i].id && c[i].id.match(/^content_ids:[0-9]+$/)) {

                c[i].onchange = function() {
                    if (this.checked == true) {
                        FotoliaLightbox.nbCheckedCheckBox++;
                    } else {
                        FotoliaLightbox.nbCheckedCheckBox--;
                    }

                    if (FotoliaLightbox.nbAvailableCheckBox == FotoliaLightbox.nbCheckedCheckBox) {
                        $('inverseSelected').checked = true;
                    } else {
                        $('inverseSelected').checked = false;
                    }
                }

                var parent_status = c[i].parentNode.parentNode.status;
                if (parent_status != "next" && parent_status != "previous") {
                    nbAvailableCheckBox++;
                }
            }
        }

        FotoliaLightbox.nbCheckedCheckBox = 0;
        FotoliaLightbox.nbAvailableCheckBox = nbAvailableCheckBox;
    },

    //set action for evenement
    setAction: function() {
        switch(this.id) {

            //open add galery form
            case 'add_new_gallery':
                var add_gallery_form = $('add_gallery_form');
                var add_gallery_button = $('add_gallery_button');

                Element.showExt(add_gallery_form);
                //Element.hideExt(add_gallery_button);
                return false;

            break;

            //close add galery form
            case 'add_gallery_cancel':
                var add_gallery_form = $('add_gallery_form');
                var add_gallery_button = $('add_gallery_button');

                Element.hideExt(add_gallery_form);
                //Element.showExt(add_gallery_button);
                return false;

            break;

            //open add galery form
            case 'edit_gallery':
                var edit_gallery_form = $('edit_gallery_form');
                var edit_gallery_button = $('edit_gallery_button');

                Element.showExt(edit_gallery_form);
                //Element.hideExt(edit_gallery_button);
                return false;

            break;

            //close add galery form
            case 'edit_gallery_cancel':
                var edit_gallery_form = $('edit_gallery_form');
                var edit_gallery_button = $('edit_gallery_button');

                Element.hideExt(edit_gallery_form);
                //Element.showExt(edit_gallery_button);
                return false;

            break;

            case 'inverseSelected':
                if (this.checked == true) {
                    FotoliaLightbox.setActionToCheckBox('check_all');
                } else {
                    FotoliaLightbox.setActionToCheckBox('uncheck_all');
                }

                break;

            //remove all checked contents
            case 'removefromlightbox':
                var pars = Form.serialize($('lightbox_form'));
                var url = '/Ajax/RemoveFromLightbox';
                var myAjax = new Ajax.Request(
                    url,
                    {
                        method: 'post',
                        parameters: pars,
                        onLoading: FotoliaAjaxActions.hrefLoading,
                        onComplete: FotoliaAjaxActions.XHRResponseTextCallback
                    }
                );

                return false;
            break;

            //add to shopping cart all checked contents
            case 'addtoshoppingcarts':
                var pars = Form.serialize($('lightbox_form'));
                var url = '/Ajax/AddToShoppingcart';
                var myAjax = new Ajax.Request(
                    url,
                    {
                        method: 'post',
                        parameters: pars,
                        onLoading: FotoliaAjaxActions.hrefLoading,
                        onComplete: FotoliaAjaxActions.XHRResponseTextCallback
                    }
                );

                return false;
            break;

            //add move to selected lightbox all checked contents
            case 'movetolightbox':
            case 'movetolightbox_button':

                if ($('movetolightbox').value != 'none') {

                    switch (FotoliaLightbox.usedForm.id) {
                        case 'lightbox_form':
                            var url = '/Ajax/MoveToLightbox';
                            break;

                        case 'content_form':
                            var url = '/Ajax/AddToFolder';
                            break;

                        default:
                            return false;
                    }

                    var pars = Form.serialize(FotoliaLightbox.usedForm);
                    var myAjax = new Ajax.Request(
                        url,
                        {
                            method: 'post',
                            parameters: pars,
                            onLoading: FotoliaAjaxActions.hrefLoading,
                            onComplete: FotoliaAjaxActions.XHRResponseTextCallback
                        }
                    );

                    $('movetolightbox').value = 'none';
                }

                return false;
            break;

            case 'inverseMsgSelect':
                FotoliaLightbox.setActionToMsgCheckBox(this.checked);

            break;

            default:
        }
    },

    // nodes index position
    folders_index: new Array(),
    folders_index_position: new Array(),
    max_node_positon: new Array(),

    // list node and position
    getLightboxTableNodeIndex: function(folder_id) {
        var folder = $(folder_id);
        var folder_index = new Array();
        var folders_index_position = new Array();
        var max_node_positon = 0;
        var current_position = 0;

        if (folder && !FotoliaLightbox.folders_index[folder_id]) {

            for (var i = 0, l = folder.childNodes.length; i < l; i++) {
                var current_node = folder.childNodes[i]
                if(current_node.id && current_node.id.match(/^content_line(.*)$/) && !current_node.removed) {
                    var matches = current_node.id.split(':');
                    current_position++;
                    max_node_positon = current_position;

                    folder_index[current_position] = matches[1];
                    folders_index_position[current_position] = i;

                    if(matches[2]) {
                        current_node.status = matches[2];
                        current_node.id = 'content_line:' + matches[1];
                    }
                }
            }

            FotoliaLightbox.folders_index_position[folder_id] = folders_index_position;
            FotoliaLightbox.max_node_positon[folder_id] = max_node_positon;
            FotoliaLightbox.folders_index[folder_id] = folder_index;
        }
    },

    // move up a node
    moveUpContent: function(content_node_id, folder_id) {
        var position  = FotoliaLightbox.getCurrentPosition(content_node_id, folder_id);
        var new_position = position - 1;
        FotoliaLightbox.updateContentNodePosition(content_node_id, folder_id, position, new_position);
    },

    // move down a node
    moveDownContent: function(content_node_id, folder_id) {
        var position  = FotoliaLightbox.getCurrentPosition(content_node_id, folder_id);
        var new_position = position + 1;
        FotoliaLightbox.updateContentNodePosition(content_node_id, folder_id, position, new_position);
    },

    // get current node position
    getCurrentPosition: function(content_node_id, folder_id) {
        FotoliaLightbox.getLightboxTableNodeIndex(folder_id);

        for (var i = 0, l = FotoliaLightbox.folders_index[folder_id].length; i < l; i++) {
            var current_node = FotoliaLightbox.folders_index[folder_id][i]
            if(current_node == content_node_id) {
                return i;
            }
        }
    },

    // update node position
    updateContentNodePosition: function(content_node_id, folder_id, real_position, real_new_position) {
        var position = FotoliaLightbox.folders_index_position[folder_id][real_position];
        var new_position = FotoliaLightbox.folders_index_position[folder_id][real_new_position];

        if ($(folder_id)
            && FotoliaLightbox.folders_index[folder_id][real_new_position] != 'lock'
            && FotoliaLightbox.folders_index[folder_id][real_position] == content_node_id) {

            // get element
            var folder = $(folder_id);
            var moved_node = $(folder.childNodes[position].id);
            var old_node = $(folder.childNodes[new_position].id);

            // update node
            folder.replaceChild(old_node,moved_node);
            folder.insertBefore(moved_node, folder.childNodes[new_position]);

            // update index
            FotoliaLightbox.folders_index[folder_id][real_position] = FotoliaLightbox.folders_index[folder_id][real_new_position]
            FotoliaLightbox.folders_index[folder_id][real_new_position] = content_node_id;

            if (real_new_position == 1) {
                Element.hideExt($('node_up_button:' + FotoliaLightbox.folders_index[folder_id][real_new_position]));
                Element.showInline($('node_up_button:' + FotoliaLightbox.folders_index[folder_id][real_position]));
            }

            if (real_new_position == FotoliaLightbox.max_node_positon[folder_id]) {
                Element.hideExt($('node_down_button:' + FotoliaLightbox.folders_index[folder_id][real_new_position]));
                Element.showInline($('node_down_button:' +  FotoliaLightbox.folders_index[folder_id][real_position]));
            }

            if (real_position == FotoliaLightbox.max_node_positon[folder_id]) {
                Element.hideExt($('node_down_button:' + FotoliaLightbox.folders_index[folder_id][real_position]));
                Element.showInline($('node_down_button:' +  FotoliaLightbox.folders_index[folder_id][real_new_position]));
            }

            if (real_position == 1) {
                Element.hideExt($('node_up_button:' + FotoliaLightbox.folders_index[folder_id][real_position]));
                Element.showInline($('node_up_button:' +  FotoliaLightbox.folders_index[folder_id][real_new_position]));
            }

            // hide next and previous
            if (old_node.status == 'next') {
                old_node.className = 'line';
                old_node.status = '';

                moved_node.className = 'display_none';
                moved_node.status = 'next';
            }

            if (old_node.status == 'previous') {
                old_node.className = 'line';
                old_node.status = '';

                moved_node.className = 'display_none';
                moved_node.status = 'previous';
            }
        }
    }
}

Event.onDOMReady(
    function() {
        FotoliaLightbox.initAction();
        FotoliaTickets.initAction();
        FotoliaDownloadFolder.initAction();
        FotoliaReleaseFolder.initAction();
    }
);

var FotoliaHomeIntro = {
    new_index: 0,
    slideshow_content_ids: null,

    init: function() {
        // init intro and detect flash support
         this.initIntroBox();

         // init mini intro slideshow
         this.initIntroMiniSlideshow();
    },

    initIntroBox: function() {
        if ($('intro_box')) {
            var FlashIntro = new SWFObject("http://static.fotolia.com/pics/flash/coverflow/coverflow.swf", "main", "100%", "350", "8.0.0", "#E0E0E0");
            FlashIntro.addParam("wmode", "transparent");
            FlashIntro.addParam("allowScriptAccess", "always");
            FlashIntro.addParam("allowFullScreen", "true");
            FlashIntro.addVariable("xmlUrl", encodeURIComponent("http://static.fotolia.com/pics/flash/coverflow/" + current_virtual_host() + ".xml"));

            if ($('flashcontent') && FlashIntro.write("flashcontent")) {
                $('intro').addClassName('with_flash');
            }

            if ($("intro_mini")) {
                var FlashIntroMini = new SWFObject("http://static.fotolia.com/pics/flash/home_slide.swf", "home", "450px", "120px", "7", "#FFFFFF");
                FlashIntroMini.addParam("wmode", "transparent");

                FlashIntroMini.addVariable ("url", encodeURIComponent("http://static.fotolia.com/small_flash." + current_virtual_host() + ".xml"));
                FlashIntroMini.write("intro_mini");
            }
        }

        if ($('categories')) {
            var FlashCateg = new SWFObject("http://static.fotolia.com/pics/flash/categories/categories.swf", "cat", "100%", "145px", "8.0.0", "#E0E0E0");
            FlashCateg.addParam("wmode", "transparent");
            FlashCateg.addParam("allowScriptAccess", "always");
            FlashCateg.addParam("allowFullScreen", "true");
            FlashCateg.addVariable("xmlURL", encodeURIComponent("http://static.fotolia.com/pics/flash/categories/" + current_virtual_host() + ".xml"));
            FlashCateg.addVariable("time", "5");
            FlashCateg.addVariable("transition", "1");

            if ($('catflash') && FlashCateg.write("catflash")) {
                $('categories').addClassName('with_flash');
            }
        }
    },

    initIntroMiniSlideshow: function() {
        if (!$('intro_box2')) {
            return false;
        }

        if ($('link_mini_0')) {
            // get current image
            FotoliaHomeIntro.getMiniSlideshowToArray();

            // launch Slideshow
            FotoliaHomeIntro.miniSlideshow();
        }
    },

    getMiniSlideshowToArray: function() {
        var c = document.getElementsByTagName('img');
        var slideshow_content_ids = new Array();
        var match;
        var content_id;

        for (var i = 0, l = c.length; i < l; i++) {
            if (c[i].id && c[i].id.match(/^mini_[0-9]+$/)) {
                match =  /(.*)\/([0-9]+)\.jpg$/.exec(c[i].src);
                content_id =  match[2];
                slideshow_content_ids.push(content_id);
            }
        }

        FotoliaHomeIntro.slideshow_content_ids = slideshow_content_ids;
        return slideshow_content_ids;
    },

    miniSlideshow: function() {
        var error = false;
        var random_id = Math.floor(Math.random() * FotoliaHomeIntro.slideshow_content_ids.length);

        var indexcontentids = FotoliaHomeIntro.indexcontentids;

        FotoliaHomeIntro.new_index = (FotoliaHomeIntro.new_index + 1) % indexcontentids.length;

        var new_image_id = indexcontentids[FotoliaHomeIntro.new_index];

        // test if already display
        for (var i = 0, l = FotoliaHomeIntro.slideshow_content_ids.length; i < l; i++) {
            // if already display
            if (FotoliaHomeIntro.slideshow_content_ids[i] == new_image_id) {
                error = true;
                break;
            }
        }

        if(error) {
            FotoliaHomeIntro.miniSlideshow();
        } else {
            var img_id = $('mini_' + random_id);
            var link_id = $('link_mini_' + random_id);

            // delete current image from slideshow_content_ids and set new
            FotoliaHomeIntro.slideshow_content_ids[random_id] = new_image_id;

            link_id.href ='/id/' + new_image_id;
            tmp_img = new Image();
            tmp_img.src = 'http://static.fotolia.com/photos_mini_index/' + new_image_id + '.jpg';

            tmp_img.onload = function() {
                img_id.src = 'http://static.fotolia.com/photos_mini_index/' + new_image_id + '.jpg';
                window.setTimeout("FotoliaHomeIntro.miniSlideshow();", 1000);
            }
        }
    }
}

var FotoliaUploadContentForm = {
    // init content Index From
    init: function() {

        if (!$('upload_content')) {
            return false;
        }

        // init action button
        FotoliaUploadContentForm.initActionButton();
    },

    // init form action for buttons
    initActionButton: function() {
        var action_buttons = new Array(
            'upload_content_form'
        );

        for (var i = 0, l =  action_buttons.length; i < l; i++) {
            if($(action_buttons[i])) {
                button = $(action_buttons[i]);
                button.onsubmit = FotoliaUploadContentForm.setAction;
            }
        }
    },

    // set action for evenement
    setAction: function() {
        var condition_1 = $('condition_1');
        var condition_2 = $('condition_2');
        var condition_3 = $('condition_3');
        var condition_4 = $('condition_4');

        switch (this.id) {
            case 'upload_content_form':
                if (!condition_1.checked
                    || !condition_2.checked
                    || !condition_3.checked
                    || !condition_4.checked) {
                    alert(_('You cannot upload your photos on Fotolia if you do not accept all "conditions of use".'));
                    return false;
                }

                if (multi_selector.count <= 1) {
                    alert(_('Please select a file from you computer.'));
                    return false;
                }

                switch (BrowserDetect.browser) {
                    case 'Safari':
                    case 'Explorer':
                        break;

                    default:
                        break;
//                         FotoliaUploadContentForm.beginUpload(this, this.progress_key.value);
//                         this.target = 'upload_iframe';
//                         this.action = this.action + '?in_iframe=on';
                }

                return true;
                break;

            default:
                //alert('No action for : '  + this.id);
        }

        return false;
    },

    callbackSuccess: function(request) {
        var response = eval('(' + request.responseText + ')');

        if (!response['done']) {
            if (response['total']) {
                var progress_percentage = Math.round(((response.current * 100) / response.total)) + '%';
                $('upload_progress_bar').style.width = progress_percentage;
                $('upload_progress_text').update(progress_percentage);
                //$('progress_information').update(response.current + ' / ' + response.total);
            }
        } else if (response['done'] == 1) {
            var progress_percentage = '100%';
            $('upload_progress_bar').style.width = progress_percentage;
            $('upload_progress_text').update(progress_percentage);

            /*
            if (response['total']) {
                $('progress_information').update(response.current + ' / ' + response.current);
            }
            */

            $('upload_progress_text').update(response.message);
            FotoliaUploadContentForm.periodialUpdater.stop();
        }
    },

    uploadFinish: function() {
        Element.hideExt($('upload_progress'));

        var iframe_doc = $('upload_iframe').contentDocument;
        var o = iframe_doc.getElementById('return_location');

        if (o) {
            window.location = o.firstChild.nodeValue;
        }

        var o = iframe_doc.getElementById('error_list');

        if (o) {
            Element.showExt($('upload_progress_finish'));
            $('upload_progress_finish').update(o.innerHTML);
        }
    },

    callbackFailure: function(request) {
        $('upload_progress_text').update(_('Upload failed'));
    },

    beginUpload: function(form, progress_key) {
        Element.hideExt($('upload_progress_finish'));
        Element.showExt($('upload_progress'));
        FotoliaUploadContentForm.periodialUpdater = new Ajax.PeriodicalUpdater(
            '',
            FotoliaUploadContentForm.download_host + '/Member/Contents/Upload/Http/AjaxCallback?nosession=1&amp;progress_key=' + progress_key,
            {
                'decay': 1,
                'frequency' : 1,
                'method': 'post',
                'parameters': 'progress_key=' + progress_key,
                'onSuccess' : FotoliaUploadContentForm.callbackSuccess,
                'onFailure': FotoliaUploadContentForm.callbackFailure
            }
        );
    }

};

Event.onDOMReady(
    function() {
        FotoliaUploadContentForm.init();
    }
);

var FotoliaFormSinglePost = {
    validateSubmit: function(submitButton)
    {
        submitButton = $(submitButton);
        if (!submitButton) {
            return true;
        }

        if (submitButton.is_posted) {
            return false;
        }

        submitButton.is_posted = true;

        return true;
    }
}

var FotoliaPopup = {
    open: function(url, title , width, height, options) {
        if (typeof(options) == 'undefined') {
            options = '';
        }

        if (typeof(width) == 'undefined') {
            width = window.outerWidth / 2;
        }

        if (typeof(height) == 'undefined') {
            height = window.outerHeight / 2;
        }

        popup = window.open(url, 'PopUp',
            ', scrollbars=yes ' +
            ', width=' + width + ' ' +
            ', height=' + height + ' ' +
            ', top=' + Math.round((window.outerHeight / 2) - (height / 2)) + ' ' +
            ', left=' + Math.round((window.outerWidth / 2) - (width / 2))
        )
    }
}

Element.FotoliaMethods = {
    visibleExt: function(element) {
        var dyn = $(element).style.display;
        var css = $(element).getStyle('display');

        switch (dyn) {
            case 'none':
                return false;
            case '':
                return (css != 'none');

            default:
                return true;
        }
    },

    toggleExt: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            Element[Element.visibleExt(element) ? 'hideExt' : 'showExt'](element);
        }
    },

    hideExt: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            element.style.display = 'none';
        }
    },

    showExt: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            element.style.display = 'block';
        }
    },

    visibleInline: function(element) {
        var dyn = $(element).style.display;
        var css = $(element).getStyle('display');

        switch (dyn) {
            case 'none':
                return false;
            case '':
                return (css != 'none');

            default:
                return true;
        }
    },

    toggleInline: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            Element[Element.visibleInline(element) ? 'hideInline' : 'showInline'](element);
        }
    },

    hideInline: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            element.style.display = 'none';
        }
    },

    showInline: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            element.style.display = 'inline';
        }
    },

    showTr: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            try {
                element.style.display = 'table-row';
            } catch (e) {
                // IE bug
                element.style.display = '';
            }
        }
    },

    fastUpdate: function(element, html) {
        $(element).innerHTML = html;
    },

    fastReplace: function(element, html) {
        element = $(element);
        if (element.outerHTML) {
            element.outerHTML = html;
        } else {
            var range = element.ownerDocument.createRange();
            range.selectNodeContents(element);
            element.parentNode.replaceChild(
                range.createContextualFragment(html),
                element
            );
        }
    },

    firstParentByTagName: function(element, tagName) {
        tagName = tagName.toUpperCase();
        element = $(element);
        while (element = element.parentNode) {
            if (element.tagName.toUpperCase() == tagName) {
                return element;
            }
        }

        return false;
    },

    insertLastSibling: function(element, type, label, attrs) {
        var node;

        element = $(element);
        if (!element || !element.parentNode) {
            return ;
        }

        node = null;
        if (element.parentNode.lastChild.nodeName.toUpperCase() == type.toUpperCase()) {
            if (attrs.className && element.parentNode.lastChild.className == attrs.className) {
                node = element.parentNode.lastChild;
                node.removeChild(node.firstChild);
                node.appendChild(document.createTextNode(label));
            }
        }
        if (!node) {
            node = document.createElement(type);
            node.appendChild(document.createTextNode(label));
            if (attrs.className) {
                node.className = attrs.className;
            }

            element.parentNode.appendChild(node);
        }
    },

    removeLastSibling: function(element, type) {
        element = $(element);
        if (!element || !element.parentNode) {
            return ;
        }

        if (!type || type.toUpperCase() == element.parentNode.lastChild.nodeName.toUpperCase()) {
            element.parentNode.removeChild(element.parentNode.lastChild);
        }
    }
}

Object.extend(Element, Element.FotoliaMethods);
Element.addMethods(Element.FotoliaMethods);

Event.onDOMReady(
    function() {
        FotoliaHomeIntro.init();
    }
);

var FotoliaPersonalData = {
    enableDisableSsnEin: function() {

        if ($('personal').checked) {
            Element.hideInline('ein_label');
            Element.hideExt('ein_inputs');
            Element.showInline('ssn_label');
            Element.showExt('ssn_inputs');
        } else if ($('company').checked) {
            Element.hideInline('ssn_label');
            Element.hideExt('ssn_inputs');
            Element.showInline('ein_label');
            Element.showExt('ein_inputs');
        }
    },

    initVAT: function()
    {
        personal = $('personal');
        company = $('company');
        vat_number_row = $('vat_number_row');

        if (vat_number_row) {
            Event.observe(personal, 'click', FotoliaPersonalData.toggleVatNumberRow.bindAsEventListener(FotoliaPersonalData, personal));
            Event.observe(company, 'click', FotoliaPersonalData.toggleVatNumberRow.bindAsEventListener(FotoliaPersonalData, company));

            if (personal.checked) {
                vat_number_row.hide();
            }
        }
    },

    toggleVatNumberRow: function(e, radio)
    {
        vat_number_row = $('vat_number_row');
        switch (radio.id) {
            case 'personal':
                vat_number_row.hide();
                break;

            case 'company':
                vat_number_row.show();
                break;
        }
    },

    initSource: function()
    {
        var source_select = $('source');
        if (source_select) {
            Event.observe(source_select, 'change', FotoliaPersonalData.toggleSource.bindAsEventListener(FotoliaPersonalData, source_select));
        }
    },

    toggleSource: function(e, select)
    {
        var tr = $('source_other_tr');
        if (tr) {
            if (select.value == -1) {
                tr.show();
            } else {
                tr.hide();
            }
        }
    }
}

// http://www.webmasterworld.com/forum91/4686.htm
function insertAtCursor(myField, myValue) {
    if (document.selection) {
        //IE support
        myField.focus();

        //in effect we are creating a text range with zero
        //length at the cursor location and replacing it
        //with myValue
        sel = document.selection.createRange();
        sel.text = myValue;

    } else if (myField.selectionStart || myField.selectionStart == '0') {
        //Mozilla/Firefox/Netscape 7+ support

        //Here we get the start and end points of the
        //selection. Then we create substrings up to the
        //start of the selection and from the end point
        //of the selection to the end of the field value.
        //Then we concatenate the first substring, myValue,
        //and the second substring to get the new value.
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}

function _(str) {
    return gettext(str)
}

function gettext(str) {
    if ((Fotolia.Localisation) && (Fotolia.Localisation[str])) str = Fotolia.Localisation[str];
    return str;
}

// This code is in the public domain. Feel free to link back to http://jan.moesen.nu/
function sprintf() {
    if (!arguments || arguments.length < 1 || !RegExp) {
        return;
    }

    var str = arguments[0];
    var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
    var a = b = [], numSubstitutions = 0, numMatches = 0;
    while (a = re.exec(str)) {
        var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
        var pPrecision = a[5], pType = a[6], rightPart = a[7];

        numMatches++;

        if (pType == '%') {
            subst = '%';
        } else {
            numSubstitutions++;
            if (numSubstitutions >= arguments.length) {
                alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
            }

            var param = arguments[numSubstitutions];
            var pad = '';
            if (pPad && pPad.substr(0,1) == "'") {
                pad = leftpart.substr(1,1);
            } else if (pPad) {
                pad = pPad;
            }

            var justifyRight = true;
            if (pJustify && pJustify === "-") {
                justifyRight = false;
            }

            var minLength = -1;
            if (pMinLength) {
                minLength = parseInt(pMinLength);
            }

            var precision = -1;
            if (pPrecision && pType == 'f') {
                precision = parseInt(pPrecision.substring(1));
            }

            var subst = param;
            if (pType == 'b') {
                subst = parseInt(param).toString(2);
            } else if (pType == 'c') {
                subst = String.fromCharCode(parseInt(param));
            } else if (pType == 'd') {
                subst = parseInt(param) ? parseInt(param) : 0;
            } else if (pType == 'u') {
                subst = Math.abs(param);
            } else if (pType == 'f') {
                subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
            } else if (pType == 'o') {
                subst = parseInt(param).toString(8);
            } else if (pType == 's') {
                subst = param;
            } else if (pType == 'x') {
                subst = ('' + parseInt(param).toString(16)).toLowerCase();
            } else if (pType == 'X') {
                subst = ('' + parseInt(param).toString(16)).toUpperCase();
            }
        }

        str = leftpart + subst + rightPart;
    }

    return str;
}


function crit_ipv_td() {

}

function parseCriteoRecommandations() {
    var o = $("cto_gsi_1749_wc");
    if (!o) {
        return;
    }

    alert(o.innerHTML);
}

function current_virtual_host() {
    var virtual_host = 'www';
    var r = /^https?:\/\/([a-z]+)\./;
    var a = r.exec(window.location.href);
    if (a) {
        virtual_host = a[1];
    }

    return virtual_host;
}

Effect.RollDown = function(element, rolledHeight, unrolledHeight) {
  element = $(element);

  var elementDimensions = element.getDimensions();
  var percentage = rolledHeight / (unrolledHeight / 100);
  return new Effect.Scale(element, 100, Object.extend({
    scaleContent: false,
    scaleX: false,
    scaleFrom: percentage,
    scaleMode: {originalHeight: unrolledHeight, originalWidth: elementDimensions.width},
    restoreAfterFinish: false,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({height: rolledHeight + 'px'}).show();
    },
    afterFinishInternal: function(effect) {
        effect.element.undoClipping();
    }
  },
  arguments[1] || {}));
}

Effect.RollUp = function(element, rolledHeight, unrolledHeight) {
  element = $(element);
  var percentage = rolledHeight / (unrolledHeight / 100);
  element.makeClipping();
  return new Effect.Scale(element, percentage,
    Object.extend({ scaleContent: false,
      scaleX: false,
      scaleTo: percentage,
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.style.height = rolledHeight + 'px';
      }
    }, arguments[1] || {})
  );
}

function makeCollapsible(collapsibleId, rolledHeight)
{
    var div = $(collapsibleId);
    var head     = div.getElementsByClassName('c_head')[0];
    var content  = div.getElementsByClassName('c_content')[0];
    var switcher = div.getElementsByClassName('c_switcher')[0];
    var switcher1 = div.getElementsByClassName('c_switcher')[1];
    var dimensions = content.getDimensions();

    div.addClassName('closed');
    unrolledHeight =  dimensions.height;
    content.style.height = rolledHeight + 'px';
    content.style.overflow = 'hidden';
    switcher.innerHTML = '<a href = "#">' + switcher.innerHTML + '</a>';
    switcher.firstDescendant().onclick = collapseOnClick(div, head, content, rolledHeight, unrolledHeight);
    if (switcher1) {
        switcher1.innerHTML = '<a href = "#">' + switcher1.innerHTML + '</a>';
        switcher1.firstDescendant().onclick = collapseOnClick(div, head, content, rolledHeight, unrolledHeight);
    }
}

function collapseOnClick(div, heading, contents, rolledHeight, unrolledHeight)
{
     return function() {

        var switcherword = div.getElementsByClassName('c_switcher')[0].firstDescendant();

        if (div.hasClassName('closed')) {
            switcherword.innerHTML = _('reduce');
            contents.style.height = rolledHeight;
            new Effect.RollDown(contents, rolledHeight, unrolledHeight);
            Element.removeClassName(div, 'closed');
        } else {
            switcherword.innerHTML = _('view more');
            contents.style.height = unrolledHeight;
            Element.addClassName(div, 'closed');
            new Effect.RollUp(contents, rolledHeight, unrolledHeight);
        }
        return false;
    };
}

var FotoliaLinkedFilters = {

    init: function()
    {
        checkboxes = new Array(
            'filter:content_type:photo',
            'filter:content_type:illustration',
            'filter:content_type:vector',
            'filter:content_type:video',
            'filters[content_type:photo]',
            'filters[content_type:illustration]',
            'filters[content_type:vector]',
            'filters[content_type:video]'
        );

        checkboxes.each(function(checkbox) {
            checkbox = $(checkbox);
            if (checkbox) {
                checkbox.observe('click', FotoliaLinkedFilters.checkToggle.bindAsEventListener(checkbox));
            }
        });

        checkbox = $('filter:content_type:all');
        if (checkbox) {
            checkbox.observe('click', FotoliaLinkedFilters.allTypeToggle.bindAsEventListener(checkbox));
        }
    },

    allTypeToggle: function()
    {
        var filterNames = new Array(
            'filters[content_type:photo]',
            'filters[content_type:illustration]',
            'filters[content_type:vector]',
            'filters[content_type:video]'
        );
        var checked = this.checked;

        filterNames.each(function(filter) {
            $A(document.getElementsByName(filter)).each(function(filter) {
                filter.checked = checked;
            });
        });
    },

    checkToggle: function()
    {
        var checkboxes = document.getElementsByName(this.name);
        var allcheckbox = $('filter:content_type:all');
        var checked = this.checked;

        $A(document.getElementsByName(this.name)).each(function(checkbox) {
            if (checked) {
                checkbox.checked = true;
            } else {
                checkbox.checked = false;
                if (allcheckbox && allcheckbox.checked) {
                    allcheckbox.checked = false;
                }
            }
        });
    }
}

Event.onDOMReady(function() {
    FotoliaLinkedFilters.init();
});

var FotoliaMemberAlternativeAddress = {
    init: function()
    {
        var checkbox = $('alternative_address_state');

        if(!checkbox) {
            return false;
        }
        addEvent(checkbox, 'change', FotoliaMemberAlternativeAddress.showHideForm);

        if (checkbox.checked) {
            Element.showExt($('member_alternative_address'));
        }
    },

    showHideForm: function()
    {
        if (this.checked == true) {
            Element.showExt($('member_alternative_address'));
        } else {
            Element.hideExt($('member_alternative_address'));
        }
    }
}

Event.onDOMReady(function() {
    FotoliaMemberAlternativeAddress.init();
    FotoliaPersonalData.initSource();
});


