sas_tmstp=Math.round(Math.random()*10000000000);sas_masterflag=1;
function SmartAdServer(sas_pageid,sas_formatid,sas_target) {
 if (sas_masterflag==1) {sas_masterflag=0;sas_master='M';} else {sas_master='S';};
 document.write('<scr'+'ipt src="http://www3.smartadserver.com/call/pubj/' + sas_pageid + '/' + sas_formatid + '/' + sas_master + '/' + sas_tmstp + '/' + escape(sas_target) + '?"></scr'+'ipt>');
}

function include(file) {
  var script  = document.createElement('script');
  script.src  = file;
  script.type = 'text/javascript';
  script.defer = true;
  document.getElementsByTagName('head').item(0).appendChild(script);
}

GridPlay = new Class({
    initialize : function(users_max_balls){
        obj=this;
        obj.TOTAL_BALLS = users_max_balls;// max balls for the game o_O
        obj.myList = Array();
        obj.resetGrid();
        obj.grid_token = '';
    },
    
    resetGrid : function(){
        obj.totalset=0;
        obj.myList= new Array();//reset this array
        obj.gridData = new Array();//define grid array
        for (var x=1;x<50;x++){
            obj.gridData.push(false);
            $$("td[GUID="+x+"]").removeClass('gselected');
            $$("td[GUID="+x+"]").setStyle('background-image','');
        }
        obj.renderBalls($('play_balls'));
    },
    setBalls:function(numbers){
    	obj.resetGrid();
    	aNumbers = numbers.split(',');
    	$each(aNumbers,function(data,key){
    		obj.setBall(data);
    	});
    },
    setBall:function(number){
        if (number == parseInt(number)){        
            if (this.isSelected(number)){
                //unselect
                if (this.totalset>0){
                    this.totalset-=1;
                    this.gridData[number]=false;
                    for (x=0;x<obj.myList.length;x++){
                        if (obj.myList[x]==number){
                            obj.myList.splice(x,1);
                        }
                    }
                    //$$("td[UID="+number+"]").toggleClass('gselected');
                    
                    $$("td[GUID="+number+"]").setStyle('background-image','');
                    //background-image : url(/static/img/grille/grille_selected.gif);
                    
                    obj.renderBalls($('play_balls'));
                }
            } else {
                //select
                if (this.totalset<obj.TOTAL_BALLS){
                    this.totalset+=1;
                    obj.myList.push(number);
                    this.gridData[number]=true;      
                    //$$("td[UID="+number+"]").toggleClass('gselected');
                    $$("td[GUID="+number+"]").each(function(el){
                        el.setStyle('background-image','url(/static/img/grille/grille_selected.gif?UID='+Math.random()+')');    
                        el.setStyle('background-repeat','no-repeat');
                    });   
                    
                    //background-repeat:no-repeat
                    obj.renderBalls($('play_balls'));
                } else {
                    alert(lang['str_already_selected']);
                }
            }
        }
    },
    isSelected : function(number){
        return this.gridData[number];
    },
    selectedList : function(){
        return obj.myList;
    },
    playFavorites : function(grid){
        gp=0;this.resetGrid();
        while ((gp!=-1) && (this.totalset<obj.TOTAL_BALLS)){
            var gl = grid.length;
            var gp = grid.indexOf(',');
            var gn = grid.substring(0,gp);
            grid = grid.substring(gp+1,gl-gp+2);
            if (gp==-1){gn=grid;}
            if (!this.gridData[gn]){
                this.setBall(gn);
            } 
        }
    },
    randomPlay : function(){
        this.resetGrid();                
        while(this.totalset<obj.TOTAL_BALLS){
            var ran=(Math.round(Math.random()*100)%49)+1;
            if (!this.gridData[ran]){
                this.setBall(ran);
            } 
        }
    },
    renderBalls : function(render){
        render.empty();
        $each(obj.myList,function(data,key){
            render.adopt(
            	//new Element('img',{'src':'/static/img/grille/'+data+'.gif'})
                new Element('div',{'class':'grille_boule marron font16','id': 'boule_'+data})
            );
            $('boule_'+data).set('html',data);
           	//$('grille_selection').setStyle('display','block');
        });
    },
    submitGame : function(){
        if (this.totalset==obj.TOTAL_BALLS){
            //var u='?grille='+obj.myList.toString();
            if (($('addtofavorites')!=undefined) && ($('addtofavorites').get('checked')==true)){
                var requestAdd = '&favorite=true';
            } else {
                var requestAdd = '&favorite=false';
            }
            var u='/grille/valid?grille='+obj.myList.toString()+requestAdd+"&grid_token="+obj.grid_token;
            popupID='popup';
        	window.open(u,popupID,'directories=no,menubar=no,status=no,location=no,scrollbars=no,resizable=no,height=301,width=250,left=100,top=100');
            top.document.location.href = this.ads_url;
            //$('myGridSubmit').submit();//submit the form
        } else {
            alert(lang['str_do_select']);
        }
    },
    saveFavorites : function(){
    	
        var myRequest = new requestManager();
        requestData={
           'action' : 'saveToFavorites',
           'grid' : obj.myList
        };
        myRequest.request(requestData,null,null,'/libs/grillePlay',obj.saveFavoritesCB);
        
    },
    saveFavoritesCB : function(r){
    	
        switch(r.error){
            case 0 :
                error_str = lang['str_saveSuccessfull']; 
                break;
            case 103 :
            	error_str = lang['str_gridNotSet'];
            	break;
            case 104 :
            	error_str = 'Veuillez choisir 9 numéros afin de pouvoir enregistrer cette grille dans vos favoris.';
            	break;
            case 105 :
            	error_str = 'Cette grille à déjà été enregistrée dans vos favoris';
            	break;
            case 20001 : //error from m_grille (too many number in your favorites)
            	error_str = lang['str_tooManyFav'];
            	break;
            default :
            	error_str = 'unknow error';
            	break;
        }
        new MooDialog.Alert(error_str);
        
        if(obj.myList.length > 0 && !r.error){
        	//console.log("add");
            favAdded = obj.myList.join(',');
            favAddedAff = obj.myList.join(' - ');
            $('listFav')
            	.getLast()
            	.clone()
            	.inject('listFav')
            	.set('rel',favAdded)
            	.setStyle('display','block')
            	.getChildren('.nums')
            	.set('html',favAddedAff)
            	.addEvent('click',function(e){
                	obj.selectFav(this);
                })
           		.getPrevious()
       			.addEvent('click',function(e){
               		e.stop();
               		grille.deleteFavorite(this.getParent().get('rel'));
               		this.getParent().destroy();
               	});
        }
    },
    
    selectFav : function(el){
    	obj.setBalls(el.getParent().get('rel'));
    	$('menu-deroulant').setStyle('display','none');
    },
    
    deleteFavorite: function(numbers){
    	var myRequest = new requestManager();
        requestData={
           'favorite' : numbers
        };
        myRequest.request(requestData,null,null,'/grille/deleteFavorite/');
    },
    checkSelected: function() {
        if (this.totalset==obj.TOTAL_BALLS){
            return true;
        } else {
            alert(lang['str_do_select']);
            return false;
        }
    }
});

function prizeDesc(id){
    var wid=Math.round(Math.random()*100);
    var width=300;
    var height=300;
    var left=(screen.width-width)/2;
    var top=(screen.height-height)/2;
    param='width='+width+',height='+height+',top='+top+',left='+left+',scrollbars=no';
    window.open('/prizes/desc?id='+id,wid,param);
    return false;
}
window.addEvent('domready', function() {
	if(typeof SqueezeBox  != "undefined") {
	    SqueezeBox.initialize({
	    	parse: 'rel',
	    	handler:'iframe'
	    });
	    SqueezeBox.assign($$('a.boxed'));
	}
});


window.addEvent("domready",function genericAction() {
	//addMooDialog($$('.reglement'),'/info/display/reglement',700,500);
	
    if($('offre_stop')) {
        //console.log("coucou 1");
        //console.log($('offre_stop'));
        $$('span[id=offre_stop]').addEvent("click",function() {
            
            var request = new Request({
                url:"/offre/stop/"+this.get("camp_id"),
                onSuccess:setTimeout("top.document.location.href='/grille/play'", 1000)
            }).send();
            
        });
    }
    if($('offre_later')) {
        //console.log("coucou 2");
    	$$('span[id=offre_later]').addEvent("click",function() {
    		top.document.location.href="/grille/play";
    	});
    }
    if($('sky8_logo')) {
    	$('sky8_logo').addEvent('click',function() {top.document.location.href='/';});
    }
	$$('.button-wrapper-center').each(function(el) {
		width = el.getChildren().getSize()[0].x;
		el.setStyle("width",width+"px");
	});    
});

function strpos (haystack, needle, offset) {
    // Finds position of first occurrence of a string within another  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/strpos    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman    
    // +   bugfixed by: Daniel Esteban
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14    var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
	var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}
var IE6 = false /*@cc_on || @_jscript_version <= 5.7 @*/;

function printf(a){
    //o_O this function do a little like c printf
    //replace %v from  parsed string by personal variables
    for (x=1;x<arguments.length;x++){
        var i = a.indexOf("%v");
        if (i>-1){
            var l = a.substr(0,i);
            var r = a.substr(i+2,l.length);
            a = l +arguments[x]+ r;
        }
    }
    return a;
}

function updateClock (currentTime) {
	if(currentTime == undefined)
		var currentTime = new Date();

	var currentHours = currentTime.getHours ( );
	var currentMinutes = currentTime.getMinutes ( );
	var currentSeconds = currentTime.getSeconds ( );

	// Pad the minutes and seconds with leading zeros, if required
	currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
	currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

	// Choose either "AM" or "PM" as appropriate
	//var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";

	// Convert the hours component to 12-hour format if needed
//	currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

	// Convert an hours component of "0" to "12"
//	currentHours = ( currentHours == 0 ) ? 12 : currentHours;

	// Compose the string for display
//	var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
	var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds;

	// Update the time display
	document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}

/* CONFIDENTIALITE */
var confid = Object();
window.addEvent('domready',function() {
	if($('confidentialite'))$('confidentialite').addEvent('click',function(e){
                                if(e)  e.stop();
		urlTab = this.get('rel').split('/');
		var popupHeight = ((parseInt(urlTab[3])+parseInt(urlTab[4])+parseInt(urlTab[5]))*65)+110;
		confid = new MooDialog.Request(this.get('rel'),null,{
			size:{
				width: 400,
				height: popupHeight
			},
			offset:{
				y:1
			}
		});	
	});
});

function parrainage_facebook(){
	FB.Connect.requireSession();
}

function showFlash(){
	$$('.flash').setStyle('display','block');
}

function hideFlash(){
	$$('.flash').setStyle('display','none');
}

function bonusmail(){
	confid = new MooDialog.Request('/users/confidentialite/1/0/0',null,{
		size:{
			width: 400,
			height: 170
		},
		offset:{
			y:1
		},
		onOpen : hideFlash,
	    onClose : showFlash
	});
}

function horoscope(){
	
}

function alert(str){
	new MooDialog.Alert(str);
}

function showFlash(){
	if($$('.flash'))$$('.flash').setStyle('display','block');
}

function hideFlash(){
	if($$('.flash'))$$('.flash').setStyle('display','none');
}


var mooDialog;
function addMooDialog(el,url,w,h) {
	
	el.addEvent('click',function(e){
		e.stop();
		mooDialog = new MooDialog.Request(url,null,{
			size:{
				width: w,
				height: h
			},
			offset:{
		        x: 0,
		        y: 0
		    },
		    onOpen : hideFlash,
		    onClose : showFlash
		});
	});  
}

/*** LOGIN ***/

window.addEvent('domready', function() {
	
	if($('login_pass_to_hide')){
		$('login_pass_to_hide').addEvent('focus',function(){
			this.setStyle('display','none');
			if($('login_pass')){
				$('login_pass').setStyle('display','block');
				$('login_pass').focus();
			}
		});
	}

	if($('login_pass')){
		$('login_pass').addEvent('blur',function(){
			if(this.get('value')=="Mot de passe" || this.get('value')==""){
				if($('login_pass_to_hide'))$('login_pass_to_hide').setStyle('display','block');
			}
		});
	}
	
	if($('login_pass_direct')){
		$('login_pass_direct').value = "";
		$('login_pass_direct').focus();
	}
	
	if($('login-form')) {
		myCheckLogin = new myFormCheck('login-form',{
			display : {tipsOffsetY:5},
			onValidateSuccess:saveLogin
		});
	}
	if ($('forgot_pass_button')){
		//SqueezeBox.assign($('forgot_pass_button'),{size: {x: 300, y: 150}});	
		addMooDialog($('forgot_pass_button'),'/info/display/forgot_pass',400,200);
		
	}
	
    if ($('captcha_refresh'))
        $('captcha_refresh').addEvent('click',function(){
            if ($('captcha_img'))
                $('captcha_img').set('src','/captcha/display/truc.png?id='+Math.random())
        })
    
    
    
    
});

function saveLogin() {
    var req = new Request.JSON({
        url:"/users/identification",
        method:'post',
        onRequest:function(r) {
            
        },
        onSuccess:function(r) {
        	//alert(r);
            __error = r.msg;
            __strError = r.lang;
            
            if(typeof(__error) == "object" && __error != null) {
            
                $each(__error,function(val,prop) {
                    if($(prop)) {
                        str = __strError[val];
                        if(val == 'required' || val == 'quest') {
                            str = str.replace("#FIELD#",'"'+$(prop).get("id")+'"');
                        } else if(val.contains("=")) {
                            _data = val.split("=");
                            str = __strError[_data[0]].replace('#FIELD#','"'+$(prop).get("id")+'"');
                            str = str.replace('#CONTRAINTE#',_data[1]);
                        }
                        $(prop).errors.push(str);
                        myCheckLogin.addError($(prop));                        
                    }
                });
            } else {
                location.href = "/dispatch/from/post_login";
            }
        },
        onFailure:function(r) {
            
        }
    }).send($('login-form'));
}

    
    
    
function genCitiesList(selecttedCity){
    getCitiesList = function(cp){
        var req = new Request.JSON({
            url:"/libs/getcities/"+cp,
            method:"get",
            async:false,
            onRequest:function() {
            },
            onSuccess:function(r) {
                var ville = $$('select[id=ville]')[0];
                if (ville){
                    ville.empty();
                    var maxLength = 0;
                    if (r.data.cp){
                        $$('span[id^=selectuser]').setStyle('color','black');
                        var myspan = $$('span[id^=selectuser]')[0];
                        if(selecttedCity != undefined) {
                            myspan.set('html',selecttedCity);
                        } else {
                            myspan.set('html',r.data.cp[0].NomMin);
                        }
                        var currentIndex = 0;
                        var selectedIndex = 0;
                        $each(r.data.cp,function(city, nothing){
                            maxLength = Math.max(city.NomMin.length, maxLength);
                            if (selecttedCity){
                                if (selecttedCity == city.NomMin){
                                    selectedIndex = currentIndex;
                                }
                            }
                            ville.adopt(
                                new Element('option',{"value":city.NomMin}).set('html',city.NomMin)
                            );
                            currentIndex++;
                        })
                        ville.selectedIndex = selectedIndex;
                        
                        if (selectedIndex==0){
                            if (r.data.cp[0]){
                                myspan.set('html', r.data.cp[0].NomMin);
                            }
                        } else {
                            myspan.set('html', selecttedCity);
                        }
                        selecttedCity = '';//just used the 1st time! clearing the entry
                    } else {
                        var myspan = $$('span[id^=selectuser]')[0];
                        myspan.setStyle('color','grey');
                        
                        myspan.set('html',ville.get('rel'));
                        ville.adopt(
                            new Element('option').set('html',ville.get('rel'))
                        );
                    }
                    if (navigator.appName=='Microsoft Internet Explorer'){
                        ville.setStyle('width',(((maxLength * 6.8)>120)?(maxLength * 6.8):120)+'px');
                    }
                }                        
            },
            onFailure:function() {
            }
        }).send();
    }
    
    if ($$('input[id=cp]')){
        var cp = $$('input[id=cp]').get('value');
        getCitiesList(cp);
        $$('input[id=cp]').addEvent("change",function(){
            var cp = this.get('value');
            //if (parseInt(cp) == cp){
                getCitiesList(cp);
            //}
            
        })
    }
}    

var popupagogo = new Class({
    initialize: function(options){
        
        var inst = this;
        this.mboverlay = new Element('div',{
            'style':'background-color: #000000;cursor: pointer;height: 100%;left: 0;position: fixed;top: 0;width: 100%;z-index: 9998;visibility: visible; opacity: 0.0;',
            'events':{'click' : function(){inst.hide();}}
        });
        this.height = (143 * options.length);
        this.topFrame = new Element('div',{
            'style':'width: 600px; height: '+ this.height + 'px; position: fixed; border: 2px solid rgb(48, 49, 50); padding: 4px; background: none repeat scroll 0% 0% rgb(0, 0, 0); left: 50%; top: 50%; display: block; z-index: 100000; -moz-border-radius: 10px 10px 10px 10px; -moz-box-shadow: 3px 3px rgb(0, 0, 0); opacity: 0.0; margin-left: -300px; margin-top: -'+(this.height / 2)+'px'
        })
        this.topFrame.adopt(
            new Element('img',{'style':'width: 24px; height: 24px; position: absolute; top: -16px; right: -16px; z-index: 100000; cursor: pointer;','src':'/static/js/bumpbox/closed.png','events':{'click':function(){inst.hide();}}})
        )
        $each(options, function(data){
            inst.topFrame.adopt(
                new Element('div',{'style':'margin: 1px; padding: 1px; text-align: left; background-color:white; width: 600px; min-height: 140px;'}).adopt(
                    new Element('img',{
                        'src':data.img,
                        'style':'float: left',
                        'class':'photo'
                    }),
                    new Element('div',{'class':'roundedbox_text', 'style':'margin: 10px 10px 0 143px;'}).adopt(
                        new Element('h2',{'class':'pourpre_lt'}).adopt(
                            new Element('strong').set('text', data.title)
                        ),
                        new Element('div',{'class':'roundedbox_desc'}).set('html',data.content)
                    )
                )
            )
        })
        this.mboverlay.setOpacity(0);
        this.topFrame.setOpacity(0);
        this.mboverlay.fade(0);
        this.topFrame.fade(0);
        document.body.adopt(
            this.mboverlay,
            this.topFrame
        )
        return this;
    },
    show: function(){
        this.mboverlay.fade('0.4');
        this.topFrame.fade('1');
        return this;
    },
    hide: function(){
        this.mboverlay.fade('0');
        this.topFrame.fade('0');
        return this;
    }
});

