var ajaxDir = "/scr/ajax/";
var is_ie = document.all;
var truebody = document.documentElement;
var mX = 0;
var mY = 0;
var	myDate = new Date();
var js_gmt_offset = myDate.getTimezoneOffset();
var myImg;


if(!is_ie)
{
	document.addEventListener('mousemove', function(e) 
		{
			mX = e.pageX;
			mY = e.pageY;
		}, true);
}
else
{
	document.attachEvent('onmousemove', function(e) 
		{
			mX = e.clientX + truebody.scrollLeft;
			mY = e.clientY + truebody.scrollTop;
		});
}


function hide_show_tag(tag,show)
{
	if(show)
		state = 'visible';
	else
		state = 'hidden';
		
 	var all_tags = document.getElementsByTagName(tag);

	num_tags = all_tags.length;
	
	for(var i=0;i<num_tags;i++)
		all_tags[i].style.visibility = state;	
}


function grayOut(vis, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {}; 
  var opacity = options.opacity || 80;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  dark=myLayer('dark',1000050);
  dark.style.top = '0px';                           
  dark.style.left = '0px'; 
	dark.style.cursor = 'wait';       
	                    
  if (vis) {
  	
    pageSize();
  	hide_show_tag('object',0);
  	
    dark.style.opacity=opaque;                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')'; 
    dark.style.backgroundColor=bgcolor;  
    dark.style.width= contentsWidth+'px';
    dark.style.height= Math.max(contentsHeight, windowHeight)+'px';
    dark.style.display='block';                          
  } else {
			hide_show_tag('object',1);
    	$("#dark").fadeOut("slow");
  }
}

//
		
var contentsWidth = 0;
var contentsHeight = 0;
var windowWidth = 0;
var windowHeight = 0;

function pageSize()
{			
	
	windowWidth = window.innerWidth ? window.innerWidth : truebody.clientWidth;
	windowHeight = window.innerHeight ? window.innerHeight : truebody.clientHeight;		

	contentsWidth = truebody.offsetWidth;
	contentsHeight = truebody.offsetHeight;
	
	if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) 
	{
	  contentsWidth = Math.max(truebody.scrollWidth, contentsWidth);
 	 	contentsHeight = Math.max(truebody.scrollHeight, contentsHeight);
 	} 
 	
}


function myLayer(layerId,z)
{
	var mLayer = document.getElementById(layerId)
	if(!mLayer)
	{
		var tbody = document.getElementsByTagName("body")[0];
	 	var tnode = document.createElement('div');          
	  tnode.style.position='absolute';                 
	  tnode.style.overflow='hidden';                               
	  tnode.style.display='none';                      
	  tnode.style.zIndex=z;
	  tnode.id=layerId;                  
	  tbody.appendChild(tnode);                            
		var mLayer = document.getElementById(layerId)
	}
	return mLayer;
}


		
function loadImg(imag,keep_open)
{
	myImg = new Image();
	myImg.src = imag;
	
	showImg(keep_open);		
}



function showImg(keep_open)
{
	
	basicPosition();
	
	if(myImg.complete)
	{
		// hide the loading animation
		showLoadLayer('hide');
									
		imgHolder = myLayer('imgHolder',1000100);
		$("select").css("visibility","hidden");
		$("#imgHolder").fadeIn("slow");
		var wall_color = document.getElementById('wall_color') ? document.getElementById('wall_color').value : '';
		imgHolder.style.background = wall_color + " url("+myImg.src+") no-repeat center center";
		imgHolder.style.width = myImg.width + 'px';
		imgHolder.style.height = myImg.height + 'px';
		imgHolder.style.cursor = 'pointer';
		imgHolder.style.padding = '35px';
		imgHolder.onclick = function(){
			if(keep_open)
			{
				return false;
			}
			else
			{ 
				$("#imgHolder").fadeOut("slow");
				setTimeout( function() {
					grayOut(0);
					$("select").css("visibility","visible");
				}, 350 ); 
				delete myImg;
			}
		};
		imgHolder.style.left = ((windowWidth/2)-(myImg.width/2)) + "px";
		imgHolder.style.top = ((windowHeight/2)-(myImg.height/2)+scrollDistance) + "px";

		grayOut(1);
	}
	else
	{	
		// show the loading animation
		showLoadLayer();
		
		setTimeout("showImg()", 250);
	}
	
}

//

function basicPosition()
{
	pageSize();
	scrollDistance = getScrollY();
	loadLayer = myLayer('loadLayer',1000999);
}

//

function showLoadLayer(val)
{
	basicPosition();
	
	if(val=='hide')
	{
		$("#loadLayer").fadeOut("slow");
		return;
	}
	
	$("#loadLayer").fadeIn("fast");
	loadLayer_x = 208;
	loadLayer_y = 13;
	
	loadLayer.innerHTML = "<div style='cursor:wait;'><img style='border:1px solid #ddd; width:"+loadLayer_x+"px;height:"+loadLayer_y+"px;' src=img/loadingAnimation.gif /></div>";
	loadLayer.style.left = (mX-loadLayer_x/2) + "px";
	loadLayer.style.top = (mY-loadLayer_y/2) + "px";
}

//

function getScrollY()
{		
	var y=0;
	if (self.pageYOffset>=0) // all except Explorer
	{
		y = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop>=0)
		// Explorer 6 Strict
	{
		y = document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		y = document.body.clientHeight;

	}
	
	scrl = (y==windowHeight) ? 0:y;
	return scrl;
}


//
//


 function colorPicker(params)
  {
    var picker = this;
    var enablepick = false;
    var enablevalue = false;
    var pickrow = 0;
    var pickcol = 0;
    this.callback = params.callback?params.callback:function(color){alert('You picked ' + color );};
    this.websafe  = params.websafe?params.websafe:false;
 
    this.cellsize = parseInt(params.cellsize?params.cellsize:'10px', 10);
    this.side     = params.granularity?params.granularity:18;
    var valuecol = this.side + 1;
    var valuerow = this.side - 1;

    this.value = 1;
    this.saved_cells = null;
    this.table = document.createElement('table');
    this.table.cellSpacing = this.table.cellPadding = 0;
    this.table.onmouseup = function()
    {
    	 enablepick = false;
    	 enablevalue = false;
    };
    this.tbody = document.createElement('tbody');
    this.table.appendChild(this.tbody);
    this.table.style.border = '1px solid WindowFrame';
    this.table.style.backgroundColor = '#fff';
 

    this.constrain_cb = document.createElement('input');
    this.constrain_cb.type = 'checkbox';




    function toHex(dec)
    {
      var h = dec.toString(16);
      if(h.length < 2) { h = '0' + h; }
      return h;
    }

 
    function tupleToColor(tuple)
    {
      return '#' + toHex(tuple.red) + toHex(tuple.green) + toHex(tuple.blue);
    }

 
    function nearestPowerOf(num,power)
    {
      return Math.round(Math.round(num / power) * power);
    }



    function doubleHexDec(dec)
    {
      return parseInt(dec.toString(16) + dec.toString(16), 16);
    }

  
    function rgbToWebsafe(color)
    {
      // For each take the high byte, divide by three, round and multiply by three before rounding again
      color.red   = doubleHexDec(nearestPowerOf(parseInt(toHex(color.red).charAt(0), 16), 3));
      color.blue  = doubleHexDec(nearestPowerOf(parseInt(toHex(color.blue).charAt(0), 16), 3));
      color.green = doubleHexDec(nearestPowerOf(parseInt(toHex(color.green).charAt(0), 16), 3));
      return color;
    }

   
    function hsvToRGB(h,s,v)
    {
      var colors;
      if(s === 0)
      {
        // GREY
        colors = {red:v,green:v,blue:v};
      }
      else
      {
        h /= 60;
        var i = Math.floor(h);
        var f = h - i;
        var p = v * (1 - s);
        var q = v * (1 - s * f);
        var t = v * (1 - s * (1 - f) );
        switch(i)
        {
          case 0: colors =  {red:v, green:t, blue:p}; break;
          case 1: colors =  {red:q, green:v, blue:p}; break;
          case 2: colors =  {red:p, green:v, blue:t}; break;
          case 3: colors =  {red:p, green:q, blue:v}; break;
          case 4: colors =  {red:t, green:p, blue:v}; break;
          default:colors =  {red:v, green:p, blue:q}; break;
        }
      }
      colors.red = Math.ceil(colors.red * 255);
      colors.green = Math.ceil(colors.green * 255);
      colors.blue = Math.ceil(colors.blue * 255);
      return colors;
    }

    /** Open the color picker
     *
     * @param string anchorage pair of sides of element to anchor the picker to
     *   "top,left" "top,right" "bottom,left" or "bottom,right"
     * @param HTML_ELEMENT element the element to anchor the picker to sides of
     *
     * @note The element is just referenced here for positioning (anchoring), it
     * does not automatically get the color copied into it.  See the usage instructions
     * for the class.
     */

    this.open = function(anchorage,element,initcolor)
    {
      this.table.style.display = '';

      this.pick_color();
 
      // Find position of the element
      this.table.style.position = 'absolute';
      var e = element;
      var top  = 0;
      var left = 0;
      do
      {
        top += e.offsetTop;
        left += e.offsetLeft;
        e = e.offsetParent;
      }
      while(e);

      var x, y;
      if(/top/.test(anchorage))
      {
        if(top - this.table.offsetHeight > 0)
        {
          this.table.style.top = (top - this.table.offsetHeight) + 'px';
        } 
        else
        {
        	  this.table.style.top = 0;
        }
      }
      else
      {
        this.table.style.top = (top + element.offsetHeight) + 'px';
      }

      if(/left/.test(anchorage))
      {
        this.table.style.left = left + 'px';
      }
      else
      {
        if(left - (this.table.offsetWidth - element.offsetWidth) > 0)
        {
          this.table.style.left = (left - (this.table.offsetWidth - element.offsetWidth)) + 'px';
        }
        else
        {
        	  this.table.style.left = 0;
        }
      }
     // IE ONLY - prevent windowed elements (<SELECT>) to render above the colorpicker
      /*@cc_on
      this.iframe.style.top = this.table.style.top;
      this.iframe.style.left = this.table.style.left;
      @*/
    };

    function pickCell(cell)
    {
        if((cell.hue >= 195  && cell.saturation > 0.5) || 
        		(cell.hue === 0 && cell.saturation === 0 && cell.value < 0.5) || 
        		(cell.hue !== 0 && picker.value < 0.75))
        {
          cell.style.borderColor = '#fff';
        }
        else
        {
          cell.style.borderColor = '#000';
        }
        pickrow = cell.thisrow;
        pickcol = cell.thiscol;
     }
    
    function pickValue(cell)
    {
        if(picker.value < 0.5)
        {
           cell.style.borderColor = '#fff';
        }
        else
        {
        	  cell.style.borderColor = '#000';
        }
        valuerow = cell.thisrow;
        valuecol = cell.thiscol;
    }
    
    function unpickCell(row,col)
    {
    	  picker.saved_cells[row][col].style.borderColor = picker.saved_cells[row][col].colorCode;
    }
    
    /** Draw the color picker. */
    this.pick_color = function()
    {
      var rows, cols;
      var picker = this;
      var huestep = 359/(this.side);
      var saturstep = 1/(this.side - 1);
      var valustep  = 1/(this.side - 1);
      var constrain = this.constrain_cb.checked;
      

      if(this.saved_cells === null)
      {
        this.saved_cells = [];

        for(var row = 0; row < this.side; row++)
        {
          var tr = document.createElement('tr');
          this.saved_cells[row] = [];
          for(var col = 0; col < this.side; col++)
          {
            var td = document.createElement('td');
            if(constrain)
            {
              td.colorCode = tupleToColor(rgbToWebsafe(hsvToRGB(huestep*row, saturstep*col, this.value)));
            }
            else
            {
              td.colorCode = tupleToColor(hsvToRGB(huestep*row, saturstep*col, this.value));
            }
            this.saved_cells[row][col] = td;
            td.style.height = this.cellsize + 'px';
            td.style.width = this.cellsize -2 +'px';
            td.style.borderWidth = '1px';
            td.style.borderStyle = 'solid';
            td.style.borderColor = td.colorCode;
            td.style.backgroundColor = td.colorCode;
            if(row == pickrow && col == pickcol)
              td.style.borderColor = '#000';
            td.hue = huestep * row;
            td.saturation = saturstep*col;
            td.thisrow = row;
            td.thiscol = col;
            td.onmousedown = function()
            {
              enablepick = true;
//            	 unpickCell(pickrow,pickcol);
              picker.saved_cells[pickrow][pickcol].style.borderColor = picker.saved_cells[pickrow][pickcol].colorCode;
              pickCell(this);
            };
            td.onmouseover = function()
            {
            	 if(enablepick)
            	 {
            	 	pickCell(this);
            	 }
            };
            td.onmouseout = function()
            {
            	 if(enablepick)
            	 {
    //            this.style.borderColor = picker.saved_cells[this.thisrow][this.thiscol].colorCode;
                this.style.borderColor = this.colorCode;
            	 }
            };
            td.onclick = function() { picker.callback(this.colorCode); picker.close(); };
            td.appendChild(document.createTextNode(' '));
            td.style.cursor = 'pointer';
            tr.appendChild(td);
            td = null;
          }

          // Add a blank and then a value column
          var td = document.createElement('td');
          td.appendChild(document.createTextNode(' '));
          td.style.width = this.cellsize + 'px';
          tr.appendChild(td);
          td = null;

          var td = document.createElement('td');
          this.saved_cells[row][col+1] = td;
          td.appendChild(document.createTextNode(' '));
          td.style.width  = this.cellsize -2 + 'px';
          td.style.height = this.cellsize + 'px';
          td.constrainedColorCode  = tupleToColor(rgbToWebsafe(hsvToRGB(0,0,valustep*row)));
          td.style.backgroundColor = td.colorCode = tupleToColor(hsvToRGB(0,0,valustep*row));
          td.style.borderWidth = '1px';
          td.style.borderStyle = 'solid';
//          td.style.borderColor = td.style.backgroundColor;
          td.style.borderColor = td.colorCode;
          if(row == valuerow)
          {
            td.style.borderColor = 'black';
          }
          td.hue = huestep * row;
          td.saturation = saturstep*col;
          td.hsv_value = valustep*row;
          td.thisrow = row;
          td.thiscol = col + 1;
          td.onmousedown = function()
          {
            enablevalue = true;
//            unpickCell(valuerow,valuecol);
            picker.saved_cells[valuerow][valuecol].style.borderColor = picker.saved_cells[valuerow][valuecol].colorCode;
            picker.value = this.hsv_value; 
            picker.pick_color();
            pickValue(this);
          };
          td.onmouseover = function() {
            if(enablevalue)
            {
              picker.value = this.hsv_value; 
              picker.pick_color();
              pickValue(this);
            }
          };
          td.onmouseout = function()
          {
            if(enablevalue)
            {
       //       this.style.borderWidth = 0;
       //       this.style.borderStyle = 'none';
              this.style.borderColor = this.colorCode;//'';
            }
          };
          td.style.cursor = 'pointer';
          tr.appendChild(td);
          td = null;

          this.tbody.appendChild(tr);
          tr = null;
        }

        // Add one row of greys
        var tr = document.createElement('tr');
        this.saved_cells[row] = [];
        for(var col = 0; col < this.side; col++)
        {
          var td = document.createElement('td');
          if(constrain)
          {
            td.colorCode = tupleToColor(rgbToWebsafe(hsvToRGB(0, 0, valustep*(this.side-col-1))));
          }
          else
          {
            td.colorCode = tupleToColor(hsvToRGB(0, 0, valustep*(this.side-col-1)));
          }
          this.saved_cells[row][col] = td;
          td.style.height = this.cellsize + 'px';
          td.style.width = this.cellsize -2 +'px';
          td.style.borderWidth = '1px';
          td.style.borderStyle = 'solid';
          td.style.borderColor = td.colorCode;
          td.style.backgroundColor = td.colorCode;
          td.hue = 0;
          td.saturation = 0;
          td.value = valustep*(this.side-col-1);
          td.thisrow = row;
          td.thiscol = col;
          td.onmousedown = function()
          {
            enablepick = true;
  //          unpickCell(pickrow,pickcol);
            picker.saved_cells[pickrow][pickcol].style.borderColor = picker.saved_cells[pickrow][pickcol].colorCode;
            pickCell(this);
          };
          td.onmouseover = function()
          {
            if(enablepick)
            {
              pickCell(this);
            }
          };
          td.onmouseout = function()
          {
            if(enablepick)
            {
   //           this.style.borderColor = picker.saved_cells[this.thisrow][this.thiscol].colorCode;
              this.style.borderColor = this.colorCode;
        	   }
          };
          td.onclick = function() { picker.callback(this.colorCode); picker.close(); };
          td.appendChild(document.createTextNode(' '));
          td.style.cursor = 'pointer';
          tr.appendChild(td);
          td = null;
        }
        this.tbody.appendChild(tr);
        tr = null;

        var tr = document.createElement('tr');
        var td = document.createElement('td');
        tr.appendChild(td);
        td.colSpan = this.side + 2;
        td.style.padding = '3px';


        this.tbody.appendChild(tr);
        tr = null;

        var tr = document.createElement('tr');
        var td = document.createElement('td');
        tr.appendChild(td);
        td.colSpan = this.side + 2;
        td.innerHTML = '<input type=button value=X class=btn onclick=myPicker.close() />';


			


        if ( this.websafe )
        {
        var div = document.createElement('div');
        var label = document.createElement('label');
        label.appendChild(document.createTextNode('Web Safe: '));

        this.constrain_cb.onclick = function() { picker.pick_color(); };
        label.appendChild(this.constrain_cb);
        label.style.fontFamily = 'small-caption,caption,sans-serif';
        label.style.fontSize = 'x-small';
        div.appendChild(label);
        td.appendChild(div);
        div = null;
        }

  
 

        this.tbody.appendChild(tr);
        document.body.appendChild(this.table);
        
        //put an iframe behind the table to mask select lists in ie
        // IE ONLY - prevent windowed elements (<SELECT>) to render above the colorpicker
        /*@cc_on
        if ( !this.iframe )
        {
        this.iframe = document.createElement('iframe');
        this.iframe.frameBorder = 0;
        this.iframe.src = "javascript:;";
        this.iframe.style.position = "absolute";
        this.iframe.style.width = this.table.offsetWidth;
        this.iframe.style.height = this.table.offsetHeight;
        document.body.insertBefore(this.iframe, this.table);
        }
        this.iframe.style.display = '';
        @*/
      }
      else
      {
        for(var row = 0; row < this.side; row++)
        {
          for(var col = 0; col < this.side; col++)
          {
            if(constrain)
            {
              this.saved_cells[row][col].colorCode = tupleToColor(rgbToWebsafe(hsvToRGB(huestep*row, saturstep*col, this.value)));
            }
            else
            {
              this.saved_cells[row][col].colorCode = tupleToColor(hsvToRGB(huestep*row, saturstep*col, this.value));
            }
            this.saved_cells[row][col].style.backgroundColor = this.saved_cells[row][col].colorCode;
            this.saved_cells[row][col].style.borderColor = this.saved_cells[row][col].colorCode;
          }
        }
        var pickcell = this.saved_cells[pickrow][pickcol];
        if((pickcell.hue >= 195  && pickcell.saturation > 0.5) || 
        		(pickcell.hue === 0 && pickcell.saturation === 0 && pickcell.value < 0.5) || 
        		(pickcell.hue !== 0 && picker.value < 0.75))
        {
           pickcell.style.borderColor = '#fff';
        }
        else
        {
        	  pickcell.style.borderColor = '#000';
        }
      }
    };

    /** Close the color picker */
    this.close = function()
    {
      this.table.style.display = 'none';
      // IE ONLY - prevent windowed elements (<SELECT>) to render above the colorpicker
      /*@cc_on
      if ( this.iframe ) { this.iframe.style.display = 'none'; }
      @*/
    };

  }

