// JavaScript Document

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

/// Color Picker
var ColorPicker=function(args){
	this.args = args || null
	this.color={'hsl':'','rgb':''};
	this.store_rgb=this.color.rgb=validateColor(this.args.color);
	this.color.hsl=rgbToHsl(this.color.rgb);
	this.store_opacity=this.color.opacity=this.args.connector.opacity.value || 100;
	this.sl=this.args.anchor
	this.sl.connector=this.args.connector;

	this.init = function(){
      var div = new Element('div',{'style':'position:absolute;height:170px;width:280px;top:20px;left:35px;border:1px solid;-moz-box-shadow: 5px 5px 10px;background:#cc9;color:#440;z-index:301'})
      var title= new Element('div',{'style':'display:block;height:20px;background:#440;color:#cc9;padding:2px 5px;margin:2px'}).update('Selecteur de couleur');
      var ldiv = new Element('div',{'style':'float:left;width:160px;margin-left:10px'})
      this.h_slider= new Element('input',{'type':'text','value':this.color.hsl.h,'name':'h'});
      this.s_slider= new Element('input',{'type':'text','value':this.color.hsl.s,'name':'s'});
      this.l_slider= new Element('input',{'type':'text','value':this.color.hsl.l,'name':'v'});
      this.a_slider= new Element('input',{'type':'text','value':this.color.opacity,'name':'v'});

      var cdiv = new Element('div',{'style':'width:100px;float:right'});
      var preview = new Element('div',{'style':'position:relative;width:85px;height:65px;border:1px solid;margin:10px 10px 0 0;background:url(/calendar/opacity_off.png)'});
      this.cs_value= new Element('div',{'id':'cs_value','style':'width:100%;height:100%;'});

      var cs_button= new Element('button',{'id':'cs_submit','style':'width:85px;margin:3px 0 0 0'}).update('Valider');
      var cs_cancel= new Element('button',{'id':'cs_cancel','style':'width:85px;margin:3px 0 0 0'}).update('Annuler');

      Event.observe(cs_button,'click',this.valid.bindAsEventListener(this));
      Event.observe(cs_cancel,'click',this.cancel.bindAsEventListener(this));

      div.appendChild(title);
      ldiv.appendChild(this.h_slider);
      ldiv.appendChild(this.s_slider);
      ldiv.appendChild(this.l_slider);
      ldiv.appendChild(this.a_slider);
      cdiv.appendChild(preview);
      preview.appendChild(this.cs_value);
      cdiv.appendChild(cs_button);
      cdiv.appendChild(cs_cancel);
      
      div.appendChild(cdiv);
      div.appendChild(ldiv);
      this.sl.appendChild(div);
      this.div=div;
      this._event_sliderMove=this.setColorPreview.bind(this);
      new Slider(this.h_slider,{'vmax':360,'decimal':'0','background':'url(/calendar/color_h.png)','onmove':this._event_sliderMove});
      new Slider(this.s_slider,{'vmax':100,'decimal':'0','background':'url(/calendar/color_sg.png)','onmove':this._event_sliderMove});
        this.setSaturation(this.s_slider)
        
      new Slider(this.l_slider,{'vmax':100,'decimal':'0','background':'url(/calendar/color_l.png)','onmove':this._event_sliderMove});
      this.l_slider.connector.style.backgroundColor='#'+rgbToHex(hslToRgb({'h':this.color.hsl.h,'s':this.color.hsl.s,'l':50}));
      
      new Slider(this.a_slider,{'onmove':this._event_sliderMove});
      this.a_slider.connector.style.backgroundColor='#'+rgbToHex(this.color.rgb);
      
      this.cs_value.style.backgroundColor='#'+rgbToHex(this.color.rgb);
      this.cs_value.setOpacity(this.a_slider.value/100);
      

		
      
  	}
	this.maj = function(){
    this.sl.connector.value='#'+rgbToHex(this.color.rgb);
	  this.sl.connector.colorBox.style.backgroundColor=this.sl.connector.value;
	  this.sl.connector.opacity.value=this.a_slider.value;
	  this.sl.connector.colorBox.setOpacity(this.a_slider.value/100);
	  if(this.args.onvalid)
	    	this.args.onvalid();
	    	
  }
	this.valid = function(){
	    this.maj()
	    this.div.parentNode.removeChild(this.div);
	    
	    this.sl=this.args=this.color=null;
	    
  	}
  	
  	this.cancel = function(){
	    this.color.rgb=this.store_rgb;
  	  this.a_slider.value=this.store_opacity;
  	  this.valid();
  	}
	
	
	this.setSaturation=function(){
		if(this.s_slider.connector){
	      if(!this.s_slider.connector.layer1){
		this.s_slider.connector.layer1 = new Element('div',{'style':'position:absolute;width:100%;height:100%;top:0;left:0;'});
		this.s_slider.connector.appendChild(this.s_slider.connector.layer1);
		}
		
		this.s_slider.connector.style.backgroundColor='#'+rgbToHex(hslToRgb({'h':this.color.hsl.h,'s':100,'l':50}));
		this.s_slider.connector.layer1.style.backgroundColor='#'+rgbToHex(hslToRgb({'h':0,'s':0,'l':this.color.hsl.l}));;
	        this.s_slider.connector.layer1.setOpacity(Math.abs((this.color.hsl.l-50)/50));
		}
	
	}
      
      
      
      
	this.setColorPreview=function(){
      	this.color.hsl={'h':this.h_slider.value,'s':this.s_slider.value,'l':this.l_slider.value}
	    	this.color.rgb=hslToRgb(this.color.hsl);
	      this.cs_value.style.backgroundColor='#'+rgbToHex(this.color.rgb);
	      if(this.l_slider.connector)
		this.l_slider.connector.style.backgroundColor='#'+rgbToHex(hslToRgb({'h':this.color.hsl.h,'s':this.color.hsl.s,'l':50}));
	      if(this.s_slider.connector)
		this.setSaturation();
	      if(this.a_slider.connector){
		this.a_slider.connector.style.backgroundColor=this.cs_value.style.backgroundColor;this.cs_value.setOpacity(this.a_slider.value/100);}
  	
	  this.maj();
    
    }
	
  this.init();
}

/// Slider Control

var Slider=function(el,args){
	this.args = args || {};
	el.vmin= this.args.vmin || 0;
	el.vmax= this.args.vmax || 100;
	el.decimal = this.args.decimal || 0;
	el.cvalue=el.value;
	el.background=this.args.background || '#fff url(/calendar/opacity.png)'
	this.sl=el
	

	this.init = function(el){
		 var slider = new Element('div',{'style':'position:relative;cursor:pointer;border:1px solid;height:8px;width:150px;margin-top:16px'});
		 slider.style.background=this.sl.background;
		 var cursor = new Element('div',{'id':'cursor_'+Math.random(),'style':'position:absolute;cursor:pointer;text-align:center;background:url(/calendar/cursor.png) no-repeat bottom center;margin-top:-17px;height:29px;width:21px;'})
		 
		 slider.appendChild(cursor);
		 el.parentNode.insertBefore(slider,el);

		 slider.connector=el;
		 this.sl.connector=slider;
		 slider.cursor=cursor;
		 this.sl.style.display='none';
		 
		 this._event_docMouseMove = this._docMouseMove.bindAsEventListener(this);
		 this._event_docMouseUp=this._docMouseUp.bindAsEventListener(this);

		 Event.observe(this.sl.connector, 'mousedown', this._mouseDown.bindAsEventListener(this));
		 Event.observe(slider.cursor, 'mousedown', this._mouseDown.bindAsEventListener(this));
    
		 this.setValue(el.cvalue);
	}
	
	this.setValue = function(){
	   var v=this.sl.value;
	 
	  	if (this.sl.connector.cursor.firstChild)
			this.sl.connector.cursor.removeChild(this.sl.connector.cursor.firstChild);
		this.sl.connector.cursor.appendChild(document.createTextNode(v));
		this.sl.connector.cursor.style.left=Math.floor((v - this.sl.vmin)*150/(this.sl.vmax-this.sl.vmin)-10)+'px'
    		this.sl.value=v;
	}
	
	
	this._mouseDown = function(e) {
		
		this.setValueFromPointer(e);
		
		Event.observe(document, 'mousemove',  this._event_docMouseMove);
		Event.observe(document, 'mouseup', this._event_docMouseUp);		

		Event.stop(e);
	}
	this._docMouseMove= function(e) {

		this.setValueFromPointer(e);
		
		Event.stop(e);
	}
	
	this._docMouseUp= function(e) {
		Event.stopObserving( document, 'mouseup', this._event_docMouseUp);
		Event.stopObserving( document, 'mousemove', this._event_docMouseMove);
		if(this.args.onchange)
      			this.args.onchange();
    
		Event.stop(e);
	}
	
	this.setValueFromPointer = function(e){
		    
    var mx= Event.pointer(e).x;
		var r= this.sl.connector.cumulativeOffset().left;
		var nval=Math.floor((((mx-r)/152)*(this.sl.vmax-this.sl.vmin)+this.sl.vmin)*Math.pow(10,this.sl.decimal))/Math.pow(10,this.sl.decimal);
		this.sl.value=(Math.min(this.sl.vmax,Math.max(this.sl.vmin,nval)));
   		this.setValue(this.sl.value);
   		if(this.args.onmove)
      			this.args.onmove();
	}
	this.init(el);
}



/// The Frame for Calendar Options
function FRAME_BOX(el){
  
  this.el=el;
  this.boxes = $$('#option_boxes .option_box');
  this.titles = $('option_box_title').childElements('div');
  
  this.setFocus = function(el){
    var elid=(el.textContent || el.text);
    for(var i=0;i<mthis.titles.length;i++){
      if(mthis.titles[i]==el){
        el.className='current';
        mthis.boxes[i].style.zIndex='51';
      }else{
        mthis.titles[i].className='';
        mthis.boxes[i].style.zIndex='50'
      }
    }
  }
  
  this.setSample=function(el){
    var mclass=el.name, mparameter=el.name;
    var r=el.name.match(/^([^\[]+)\[(.*)\]$/);
    if(r)
    	var mclass=r[1], mparameter=r[2];
    switch(mparameter){
    	case 'font_family':
    		var mod_el = $$('#calendar_sample .'+mclass);
    		var style = {'fontFamily' : el.value };
    		break;
    	case 'style':
    		var mod_el = $$('#calendar_sample .'+mclass);
    		if(el.value=='bold')
    			var style = {'fontWeight' : 'bold','fontStyle' : '' };
    		if(el.value=='italic')
    			var style = {'fontWeight' : '','fontStyle' : 'italic' };
    		if(el.value == 'bold italic')
    			var style = {'fontWeight' : 'bold','fontStyle' : 'italic'};
    		if(el.value == 'normal')
    			var style = {'fontWeight' : '','fontStyle' : ''};
    			
    		break;
    	case 'size':
    		var mod_el = $$('#calendar_sample .'+mclass);
    		var style = {'fontSize' : el.value +'px', 'height':el.value +'px','lineHeight':el.value +'px'};
    		break;
    	case 'bgcolor':
    		var mod_el = $$('#calendar_sample .'+mclass);
    		var style = {'backgroundColor' : el.value };
    		break;
    	case 'color':
    		var mod_el = $$('#calendar_sample .'+mclass);
    		var style = {'color' : el.value };
    		break;
    	case 'opacity':
    	case 'off_opacity':
    		var mod_el = $$('#calendar_sample .'+mclass);
    		var style = {'opacity' : el.value / 100 };
    		break;
    	case 'show':
    		var mod_el = $$('#calendar_sample .'+mclass);
    		var style = {'display' : (el.checked?'':'none')};
    		break;
    	case 'orientation':
    	case 'template':
    	   var box_form=$(el).form.getInputs('radio','page[template]');
    	   var page_orientation=$(el).form.getInputs('radio','page[orientation]');
    	   
         if(box_form[0].checked){
            var sx=83,sy=83;
         }else{
            var sx=83,sy=105;
         }
         if(page_orientation[0].checked){
            var w=sx,h=sy;
         }else{
            var w=sy,h=sx;
         }
         for(var i=1;i<5;i++){
    	     var cc = $$('#calendar_sample .c'+i);
    	       if(cc)
             cc.each(function(s){s.setStyle({'width':w+'px','right':((4-i)*(w+5)+10)+'px'});});
           
           var cc = $$('#calendar_sample .l'+i);
           if(cc)
             cc.each(function(s){s.setStyle({'height':h+'px','top':((i-1)*(h+5)+65)+'px'});});
    	    }
    	    
    	   
    	}
    	if(mod_el)
    	for(var i =0 ;i<mod_el.length; i++){
    		if(style)
    			mod_el[i].setStyle(style);
    	}
    
  }
  
  
  this.showColor = function(el){
  el=el.target;
    if(!this.colorSelector || !this.colorSelector.sl){
      this.colorSelector = new ColorPicker({'anchor':el.connector.parentNode,'connector':el.connector,'color':el.style.backgroundColor,'onvalid':function(){mthis.setSample(el.connector);mthis.setSample(el.connector.opacity)}});
    }
  }
  
  
  
  this.setAsColorSelector = function(el){
    el.style.display='none';
    var color=(el.value!=''?el.value:'#000000').replace('#','')
    var new_opacity=el.id=el.name;
    
    var r=el.name.match(/^([^\[]+)\[(.*)\]$/);
      if(r)
        new_opacity=r[1];
    el.opacity = new Element('input',{'name':new_opacity+'[opacity]','type':'text','value':100,'style':'display:none'});
    el.background = new Element('div',{'style':'position:relative;cursor:pointer;border:1px solid #022;height:20px;width:35px;float:left;background:url(/calendar/opacity_off.png)'});
    el.colorBox= new Element('div',{'id':el.name+'_div','style':'position:absolute;width:35px;height:20px;background:#'+color,'title':'Cliquer pour modifier la couleur'});
    el.background.appendChild(el.colorBox)

    el.colorBox.connector=el;
    Event.observe(el.colorBox,'click',mthis.showColor.bindAsEventListener(el));
    el.parentNode.insertBefore(el.background,el);
    el.parentNode.insertBefore(el.opacity,el);
  }
  
  this.setAsOpacitySelector = function(el){
    var r= new Slider(el,{'onmove':function(){mthis.setSample(el)}});
  }
  
  this.majFont = function(){
    els=$$('.fontselect');
    els.each(function(s){mthis.setSample(s)});
  }
  
  
  
  mthis = this;
  
  for(var i=0;i<this.titles.length;i++){
    Event.observe(this.titles[i],'click',function(){mthis.setFocus(this)});
  }
  this.boxes.elements = el.childElements('form')[0].getElements();
  
  for(var j=0;j<this.boxes.elements.length;j++){
      if(this.boxes.elements[j].className=='colorselector'){
        mthis.setAsColorSelector(this.boxes.elements[j]);
      }
      if(this.boxes.elements[j].className=='OpacitySelector'){
        mthis.setAsOpacitySelector(this.boxes.elements[j]);
      }
      if(this.boxes.elements[j].type=='checkbox' || this.boxes.elements[j].type=='radio'){
          new RadioClick(this.boxes.elements[j],function(){mthis.setSample(this.el)})
        
        
      }else{
        Event.observe(this.boxes.elements[j],'change',function(){mthis.setSample(this)});
      }
      
  	
  }
  el.childElements('form')[0].target='_blank';
  this.boxes.elements = el.childElements('form')[0].getElements();
  
  for(var j=0;j<this.boxes.elements.length;j++)
  	mthis.setSample(this.boxes.elements[j]);
  el.style.display='';
  
}

var RadioClick=function(el,func){
  this.el=el
  this.func=func
  
  this.init =function(){
  this._event_docMouseUp=this._docMouseUp.bindAsEventListener(this);
  Event.observe(this.el,'mousedown',this._mouseDown.bindAsEventListener(this))
  }
  this._mouseDown = function(e){
    Event.observe(document,'mouseup',this._event_docMouseUp)
    Event.stop(e)
  }
  
  this._docMouseUp = function(e){
    Event.stopObserving( document, 'mouseup', this._event_docMouseUp);
    this.el.checked=!this.el.checked;
    this.func();
    this.el.checked=!this.el.checked;
    Event.stop(e)
  }
  this.init();
}


// color functions
hexToRgb=function(hex) {
		//hex = this.validateHex(hex);

		var r='00', g='00', b='00';
		
		/*
		if (hex.length == 3) {
			r = hex.substring(0,1);
			g = hex.substring(1,2);
			b = hex.substring(2,3);
		} else if (hex.length == 6) {
			r = hex.substring(0,2);
			g = hex.substring(2,4);
			b = hex.substring(4,6);
		*/
		if (hex.length == 6) {
			r = hex.substring(0,2);
			g = hex.substring(2,4);
			b = hex.substring(4,6);	
		} else {
			if (hex.length > 4) {
				r = hex.substring(4, hex.length);
				hex = hex.substring(0,4);
			}
			if (hex.length > 2) {
				g = hex.substring(2,hex.length);
				hex = hex.substring(0,2);
			}
			if (hex.length > 0) {
				b = hex.substring(0,hex.length);
			}					
		}
		
		return { r:this.hexToInt(r), g:this.hexToInt(g), b:this.hexToInt(b) };
	}
rgbToHex= function (rgb) {
		return this.intToHex(rgb.r) + this.intToHex(rgb.g) + this.intToHex(rgb.b);
	}
	intToHex= function (dec){
		var result = (parseInt(dec).toString(16));
		if (result.length == 1)
			result = ("0" + result);
		return result.toUpperCase();
	}
	hexToInt= function (hex){
		return(parseInt(hex,16));
	}
	
rgbToHsl= function (rgb) {

		var r = rgb.r / 255;
		var g = rgb.g / 255;
		var b = rgb.b / 255;

		hsl = {h:0, s:0, l:0};

		var min = 0
		var max = 0;

		if (r >= g && r >= b) {
			max = r;
			min = (g > b) ? b : g;
		} else if (g >= b && g >= r) {
			max = g;
			min = (r > b) ? b : r;
		} else {
			max = b;
			min = (g > r) ? r : g;
		}
		
		hsl.l=(max+min)/2;
    hsl.s = (min==max) ? 0 : ((hsl.l>0.5) ? ((max-min)/(2-2*hsl.l)):((max-min)/(2*hsl.l)))
	
		if (!hsl.s) {
			hsl.h = 0;
		} else {
			delta = max - min;
			if (r == max) {
				hsl.h = (g - b) / delta;
			} else if (g == max) {
				hsl.h = 2 + (b - r) / delta;
			} else {
				hsl.h = 4 + (r - g) / delta;
			}

			hsl.h = parseInt(hsl.h * 60);
			if (hsl.h < 0) {
				hsl.h += 360;
			}
		}
		hsl.s= (hsl.l==1?1:hsl.s);
		hsl.s = parseInt(hsl.s * 100);
		hsl.l = parseInt(hsl.l * 100);

		return hsl;
	}

//calculate rgb component
hToC=function(x, y, h) {
  var c;
  
  if(h < 0) {
    h += 1;
  }
  if(h > 1) {
    h -= 1;
  }
  if (h<1/6) {
    c=x +(y - x) * h * 6;
  } else {
    if(h < 1/2) {
      c=y;
    } else {
      if(h < 2/3) {
        c=x + (y - x) * (2 / 3 - h) * 6;
      } else {
        c=x;
      }
    }
  }
  return Math.floor(c*255);
}

hslToRgb=function(hsl){
  var h=hsl.h/360,l=hsl.l/100,s=hsl.s/100,
    y = (l > .5)? (l + s - l *s) : l * (s + 1),
    x = l * 2 - y,
    rgb={'r':0,'g':0,'b':0};
    
    rgb.r = hToC(x, y, h + 1 / 3);
    rgb.g = hToC(x, y, h);
    rgb.b = hToC(x, y, h - 1 / 3);
  return rgb;
}
	
	validateColor=function(color){
    if(color.toUpperCase().match(/^#[A-F0-9]{6}$/)){
      return hexToRgb(color.replace('#',''));
    }
    var r;
    if(r=color.toLowerCase().match(/rgb\(([0-9]+), ([0-9]+), ([0-9]+)\)/)){
      return {'r':r[1],'g':r[2],'b':r[3]};
    }
    return {'r':255,'g':255,'b':255};
  }


var fb_calendar

window.onload=function(){
loadjscssfile("/calendar/calendar.css", "css");
fb_calendar=new FRAME_BOX($('config_frame'));
}
