/**
 * FLASH NAME must be RCISimulator because of the *$!!� makolab financial flash and IE
 */
var flashId="RCISimulator";


function openPopup(url) {
    window.open(url,"popupMap24","width=570,height=520,menubar=no,location=no,status=no,scrollbars=no,resizable=no,status=no,toolbar=no,location=no")
}

function resizeFromFlash(height,width) {
		resizeFlash(height,width);
}

var lastHeight=0;
function resizeFlash(height, width) {
	var object = document.getElementById(flashId);
	height = parseInt(height,10);
	var ratio = object.offsetWidth/parseInt(width,10);
	ratio = Math.round(ratio*100000)/100000;
	height = Math.round(height*ratio);
	
	if(lastHeight != height) {
		object.height = height;
		object.parentNode.style.height = object.height + 'px';
		lastHeight = height;
	}
}

function setConfirmStats(params) {
    //	'<IFRAME SRC="http://fls.doubleclick.net/activityi;src=2145395;type=convers9;cat=shopconv;u3=[Modele];qty=1;cost=[Revenue];ord=[OrderID]?" WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>'
    var srcStats = 'http://fls.doubleclick.net/activityi;src=2145395;type=convers9;cat=shopconv;u3=[Modele];qty=1;cost=[Revenue];ord=[OrderID]?';
    var iframe = document.getElementById('confirmStatsIframe');
    if (!iframe) {
        iframe = document.createElement('iframe');
        iframe.id = 'confirmStatsIframe';
        iframe.width = 1;
        iframe.height = 1;
        iframe.frameborder = 0;
        document.body.appendChild(iframe);
    }
    iframe.src = srcStats.replace(/\[Modele\]/,params.model)
                         .replace(/\[Revenue\]/, params.revenue)
                         .replace(/\[OrderID\]/, (new Date().getTime()+'')+Math.round(Math.random()*10000))

}
function updateMentions(arr) {
    var mentionsLegalesDiv = document.getElementById('mentionsLegales');
    mentionsLegalesDiv.innerHTML="";
    if (arr.length==0)
        updateStarMention('');
    for (var i=0; i<arr.length; i++) {
        var elm = document.createElement('span');
        elm.innerHTML = '&nbsp;&nbsp;(' + (i+1) + ')' + ' ' + arr[i] + '.';
        mentionsLegalesDiv.appendChild(elm);
    }
}

function getViewportDimensions() {
		var d = document.documentElement;
		var object = document.getElementById(flashId);
		var objectPosTop = findPos(object)[1];
		return {
			x : d.scrollLeft,
			y : window.scrollY || d.scrollTop,
			height : d.clientHeight,
			width : d.clientWidth,
			yApp : objectPosTop
		};
	}


function updateStaticMentions(array) {
    var staticMentionDiv = document.getElementById('staticMentionDiv');
    if(!staticMentionDiv) {
        staticMentionDiv = document.createElement('div');
        staticMentionDiv.className = "mentionsDiv";
        staticMentionDiv.id = 'staticMentionDiv';
        var ml = document.getElementById('mentionsLegales');
        ml.parentNode.insertBefore(staticMentionDiv,ml);
    }
    staticMentionDiv.innerHTML = array.join(', ');
}


    function updateStarMention(mention,reset) {
            var starMentionDiv = document.getElementById('starMentionDiv');
            if(!starMentionDiv) {
                    starMentionDiv = document.createElement('div');
                    starMentionDiv.id = 'starMentionDiv';
                    var ml = document.getElementById('mentionsLegales');
                    ml.parentNode.insertBefore(staticMentionDiv,ml);
            }
            if(mention=='')
            {
                    starMentionDiv.innerHTML ='';
            } else {
                    starMentionDiv.innerHTML += mention+'<br/>';
            }
    }



function goToHome() {
    var flash = document.getElementById(flashId);
    if (flash) {
        flash.goToHome();
        return false
    } else return true;
}

function executeStats(locale, params) {
    //var netstat_sitename = "renault-com";
    var netstat_countername = locale + "." + params;
    //trace('-&nbsp;'+netstat_countername+'<br/>');
    if (window.sitestat_update) sitestat_update(netstat_sitename, netstat_countername);
}

function trace() {
    var debug = document.getElementById('debug');
    if (!debug) {
        debug = document.createElement('div');
        debug.id = 'debug';
        debug.style.position = 'fixed';
        debug.style.top = 0;
        debug.style.left = 0;
        debug.style.width = '250px';
        debug.style.height = '500px';
        debug.style.border = '1px solid #000';
        debug.style.background = "#fff";
        debug.style.overflow = 'auto';
        document.body.appendChild(debug);
    }
    debug.scrollTop = debug.scrollHeight;
    debug.innerHTML+= '<br/>' + Array.prototype.slice.apply(arguments).join(', ');
}

function bugdetPlannerPopup() {
    window.open('/${componentNamespace}/static/html/popup_budgetPlanner.html?locale='+(window.renaultLocale || 'fr_FR'), 'budgetPlanner', 'width=520,height=415, scrollbars=no, menu=no, status=no, resizable=no, toolbar=no, location=no');
}

function scrollToFlashPosition(flashPosTop) {
    var object = document.getElementById(flashId);
    var objectPosTop = findPos(object)[1];
    document.documentElement.scrollTop = document.body.scrollTop = objectPosTop + flashPosTop;
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
    }
    return [curleft,curtop];
}

/* PARTIE FINANCEMENT */



// VN data must be by the components to this the page (via the component param)
var _DisplaySimulatorRenderer_ = {
    // the finance parameter will be added by the flash callback
    "deposit" : "",
    "duration" : "",
    "insurance" : "",
    "offerType" : ""
};



 function __Display_Simulator__updateFinValues() {
    //Retourne les nouvelles valeurs a l'application Flex
    var flash = document.getElementById(flashId);
    if (flash) {
        flash.updateFinanceInfo(_DisplaySimulatorRenderer_);
        return false
    } else return true;
}

// Javascript routine called by the flash when user change slider value
// code directly taken from example at http.//fin.makolab.pl
var _DisplaySimulatorRenderer_timeoutId=-1;

//var InternetExplorer = navigator.appName.indexOf("Microsoft") != -1;

function RCISimulator_DoFSCommand(command, args) {
      //var RCISimulatorObj = InternetExplorer ? RCISimulator : document.RCISimulator;
        var RCISimulatorObj = document.getElementById(flashId);
    //trace(command, args)
    if (command == "SendFinanceDataToRSite"){
        arg = args.split(",")
        // data given via the flash
        _DisplaySimulatorRenderer_.carPrice   = arg[0];
        _DisplaySimulatorRenderer_.deposit    = arg[1];
        _DisplaySimulatorRenderer_.duration   = arg[2];
        // insurrance are the concatenation of arg 5 to 7
        _DisplaySimulatorRenderer_.insurance  = arg[5] +","+arg[6] +","+ arg[7];

        _DisplaySimulatorRenderer_.offerType  = arg[11];
        _DisplaySimulatorRenderer_.genericParam = arg[14];

        // Prevention : Because huges flash simulators call, AJAX calls are delayed
        clearTimeout(_DisplaySimulatorRenderer_timeoutId);
        _DisplaySimulatorRenderer_timeoutId = setTimeout(__Display_Simulator__updateFinValues, 300);
     }
}

if (navigator.appName &&
    navigator.appName.indexOf("Microsoft") != -1 &&
    navigator.userAgent.indexOf("Windows") != -1 &&
    navigator.userAgent.indexOf("Windows 3.1") == -1)
    {
        document.write('<SCRIPT LANGUAGE=VBScript\> \n');
        document.write('on error resume next \n');
        document.write(
                'Sub RCISimulator_FSCommand(ByVal command, ByVal args)\n');
        document.write(
               ' call RCISimulator_DoFSCommand(command, args)\n');
        document.write('end sub\n');
        document.write('</SCRIPT\> \n');
    }




function toggleMe(id){
    var elm = document.getElementById(id);
    if (elm.className.match(/mentionsLegalesOpened\b/)){
        elm.className = 'mentionsLegales';
    }else{
        elm.className += ' mentionsLegalesOpened';
    }
}


//custom appli webstore
Fx.Base.implement({
    step: function(){
        var time = $time();
        if (time < this.time + this.options.duration){
            this.delta = this.options.transition((time - this.time) / this.options.duration);
            this.setNow();
            this.increase();
            this.fireEvent('onMotion', this.element);
        } else {
            this.stop(true);
            this.set(this.to);
            this.fireEvent('onComplete', this.element, 10);
            this.callChain();
        }
    }
});


//correction pour IE6, bug a un moment le title est remplace par le hash de l'url
var lastTitle = document.title;
if (document.all && window.attachEvent && /MSIE [56]/.test(navigator.userAgent)) {
    setInterval(titleChecker, 100);
}

function titleChecker() {
    var newTitle = document.title;
    if (lastTitle != newTitle) {
        if (newTitle.match(/\action=/))
            document.title = lastTitle;
        else
            lastTitle = newTitle;
    }
}

