/*
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('^http://[A-Za-z0-9_\\.]+/Ajax/([A-Za-z0-9]+)', 'gi');
            var results = regexp.exec(current[j].href);
            if (!results) {
                continue;
            }

            //Event.observe(current[j], 'click', FotoliaAjaxActions.hrefClick);
            // 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 = {
    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_');
			*/

			// here we are considering only images from mini folder
            if( current[j].src.indexOf('mini/')<0 && current[j].src.indexOf('thumb/')<0 && current[j].src.indexOf('medium/')<0)continue;
			if( current[j].src.indexOf('mini/')>=0){
				var largeSrc = current[j].src.replace('mini/', 'watermark/');
			}else if( current[j].src.indexOf('thumb/')>=0){
				var largeSrc = current[j].src.replace('thumb/', 'watermark/');
			}
            else if( current[j].src.indexOf('medium/')>=0){
				var largeSrc = current[j].src.replace('medium/', 'watermark/');
			}

            current[j].setAttribute('largeSrc', largeSrc);

            var title = current[j].getAttribute('title');
            // remove title
            current[j].setAttribute('title', '');

            var tip = '<div class="tool"><img src="' + largeSrc + '" /></div>';
            new Tooltip(current[j], tip, {'html': true, 'classname': 'FotoliaTooltipObject'});
        }
    }
}

/*
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();
    },

    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:all':
                    Event.observe(c[i], 'click', Fotolia.filtersEventBox);
                    break;
            }
        }
    },

    filtersEventBox: function(e) {
        var elm = Event.element(e);
        switch (elm.id) {
            case 'filter:content_type:photo':
                if (elm.checked) {
                    $('filter:content_type:all').checked = false;
                }
                break;
            case 'filter:content_type:illustration':
                if (elm.checked) {
                    $('filter:content_type:all').checked = false;
                }
                break;
            case 'filter:content_type:vector':
                if (elm.checked) {
                    $('filter:content_type:all').checked = false;
                }
                break;
            case 'filter:content_type:all':
                if (elm.checked) {
                    $('filter:content_type:photo').checked = false;
                    $('filter:content_type:illustration').checked = false;
                    $('filter:content_type:vector').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;
    }
}

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
    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();
    },

    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["S"] = new Array();
        licenses_possibilities["S"]["CAN"] = new Array();
        licenses_possibilities["S"]["CAN"][0] = _("Use the Work in all print  and electronic or online  materials, and web pages");
        licenses_possibilities["S"]["CAN"][1] = _("Modify image or use in derivative works");
        licenses_possibilities["S"]["CAN"][2] = _("Make back up copies");
        licenses_possibilities["S"]["CANNOT"] = new Array();
        licenses_possibilities["S"]["CANNOT"][0] = _("Resell original image");
        licenses_possibilities["S"]["CANNOT"][1] = _("Use image in any way that violates local or federal laws");
        licenses_possibilities["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["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] = _("@todo");
        licenses_possibilities["V"]["CAN"][1] = _("@todo");
        licenses_possibilities["V"]["CAN"][2] = _("@todo");
        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");

        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('S', 'M', 'L', 'XL', 'XXL');
        var content_id = FotoliaShoppingCart.retrieveIndex(this);
        var selected_license_abbr = FotoliaShoppingCart.contents_licenses[content_id];

        // 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 = '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').update(remaining_credits_string);

        if (remaining_credits < 0) {
            Element.showInline($('buy_credit_link'));
        } else {
            Element.hideInline($('buy_credit_link'));
        }
    },

    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));
            }
        }
    },

    updateShoppingcartData: function(nbContents, total_price_string, remaining_credits, remaining_credits_string)
    {
        // update shopping cart prices
        if($('totalPrice')) {
            FotoliaShoppingCart.updateNbItem(nbContents);
            FotoliaShoppingCart.updateTotalPrice(total_price_string);
            FotoliaShoppingCart.updateRemainingCredits(remaining_credits, remaining_credits_string);
        }

        if($('shoppingcart:nbcontents')) {
            FotoliaShoppingCart.updateShoppingcartNbContents(nbContents);
        }
    },

    // 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));

            // 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;
            }
        }
    },

    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) {
                    return true;
                }

                alert(_('Please check the box to accept contract and continue'));
                break;

            default:
                //alert('No action for : '  + this.id);
        }

        return false;
    }
}

Event.onDOMReady(function() {
    FotoliaShoppingCart.init();
});

var FotoliaLightbox = {
    usedForm: null,

    updateLightboxNbContents: function(nbContents)
    {
        $('current_lightbox:nbcontents').firstChild.nodeValue = nbContents;
    },

    //ini lightbox action button
    initAction: function() {

        if($('lightbox_form')){
            FotoliaLightbox.usedForm = $('lightbox_form');
        }

        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.nbAvalableCheckBox;
                    c[i].checked = true;
                    return_value[i] = c[i];
                    break;

                    case 'uncheck_all':
                    FotoliaLightbox.nbCheckedCheckBox = 0;
                    c[i].checked = false;
                    break;
                }
            }
        }

        return return_value;
    },

    nbAvalableCheckBox: 0,
    nbCheckedCheckBox: 0,

    //action for contents checkboxes
    initActionToCheckBox: function() {
        var c = document.getElementsByTagName('input');
        var return_value = '';

        var nbAvalableCheckBox = 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.nbAvalableCheckBox == FotoliaLightbox.nbCheckedCheckBox) {
                        $('inverseSelected').checked = true;
                    } else {
                        $('inverseSelected').checked = false;
                    }
                }

                var parent_status = c[i].parentNode.parentNode.status;
                if (parent_status != "next" && parent_status != "previous") {
                    nbAvalableCheckBox++;
                }
            }
        }

        FotoliaLightbox.nbCheckedCheckBox = 0;
        FotoliaLightbox.nbAvalableCheckBox = nbAvalableCheckBox;
    },

    //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;

            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();
    }
);

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')) {
            return false;
        }

        var FlashIntro = new SWFObject("http://static.fotolia.com/pics/flash/home_fotolia.swf", "home", "100%", "335", "7", "#E0E0E0");
        FlashIntro.addParam("wmode", "transparent");
        if (FlashIntro.write("flashcontent")) {
            $('intro').addClassName('with_flash');
        }

        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/halloween.xml"));
        FlashIntroMini.write("intro_mini");
    },

    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 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');
        }
    }
}

// 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[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;
}

