var imageUrl = '../../modules/Modules.ImageReplace.UI/handlers/image.ashx';
/*************************************************************
 * options parameter:
 *      font (String), required > The name of the font to be used 
 *      minwidth (Integer)	>	The minimal width of the generated image
 *      maxwidth (Integer)	>	The maximal width of the generated image
 *      forecolor (String)	>	The HTML foreground color. Black by default.
 *		    					Eg. 'red', '#ff0000'
 *      backcolor (String)	>	The HTMLbackground color. White by default
 *			    				Eg.  'red', '#ff0000'
 *      font (String)		>	The full name of the font.
 *						        Eg. 'Comic Sans MS'.
 *      fontsize (Integer)	>	The size of the font in pixels.
 *      align (String)		>	The horizontal alignment of the text inside the image.
 *		    				    Eg. 'left', 'center' or 'right'.
 */
jQuery.fn.imageReplace = function(options){
    
    if(!options)
        options = {};
	
    this.each(
        function()
        {
            if(!jQuery.className.has(this, 'imagereplaced'))
            {
				var jqthis = jQuery(this);

			    jqthis.options = options;
				jqthis.origtext = $.trim(jqthis.text());
				
				jqthis.hover(function()
				{
					//MSIE doesn't do :hover in the onmouseover yet, so wait a millisec
					setTimeout(function()
					{
						var opts = {};
						jQuery.extend(opts, jqthis.options); //make a copy
						var url = jqthis.makeImageReplaceUrl(opts);
						if (url != jqthis.url)
							jqthis.image.attr('src', url);
					}, 1)
				},
				function() {
					//MSIE doesn't do :hover in the onmouseover yet, so wait a millisec
					setTimeout(function() {
							if (jqthis.url != jqthis.image.attr('src'))
								jqthis.image.attr('src', jqthis.url);
						},
						1)
				}
					
				);

				// get the inner text
				var opts = {};
				jQuery.extend(opts, jqthis.options); //make a copy
				jqthis.url = jqthis.makeImageReplaceUrl(opts);
				jqthis.html('<img src="' + jqthis.url + '" alt="' + jqthis.origtext + '" border="0" />');
				jqthis.image = jqthis.children("img");
				
				// add a class, so we dont do the same element twice.

				jQuery.className.add(this, 'imagereplaced');
			}
        }
    )
    
    return this;
};

jQuery.fn.makeImageReplaceUrl = function(opts) {
	
    if(!opts)
        opts = {};

	var params = 't=' + urlEncode(this.origtext);

	if(opts.minwidth)
		params += '&minw=' + parseFloat(opts.minwidth);
	if(opts.maxwidth)
		params += '&mw=' + parseFloat(opts.maxwidth);
    else if(opts.width)
        params += '&mw=' + parseFloat(opts.width);

	if(!opts.font)
		opts.font = this.css("font-family");
	params += '&fn=' + urlEncode(opts.font);
	if(!opts.font)
		opts.font = this.css("font-family");

	if(!opts.fontsize)
		opts.fontsize = this.css("font-size");
	params += '&fs=' + parseFloat(opts.fontsize);
	
	if(!opts.forecolor)
		opts.forecolor = this.css("color");
		
	if (opts.forecolor != 'transparent' && typeof(opts.forecolor) != 'undefined')
	{
		if (opts.forecolor.substr(0, 3) == "rgb")
			opts.forecolor = rgb2Hex(opts.forecolor);
		params += '&fc=' + urlEncode(opts.forecolor);
	}
	
	if(!opts.backcolor)
		opts.backcolor = this.css("background-color");

	if ((opts.backcolor) && opts.backcolor.substr(0, 3) == "rgb")
		opts.backcolor = rgb2Hex(opts.backcolor);
	if (opts.backcolor && (opts.backcolor != 'transparent') && (typeof(opts.backcolor) != 'undefined'))
	{
		params += '&bc=' + urlEncode(opts.backcolor);
	}

	if ((opts.transparentcolor) && opts.transparentcolor.substr(0, 3) == "rgb")
		opts.transparentcolor = rgb2Hex(opts.transparentcolor);
	if (opts.transparentcolor)
	{
		params += '&tc=' + urlEncode(opts.transparentcolor);
	}

	if(!opts.align)
		opts.align = this.css('text-align');
	
	params += '&align=' + opts.align;
		
	var url = imageUrl + '?' + params;

	return url;
}


/*************************************************************
 *
 *
 */
function urlEncode (sText)
{
	sText = sText.replace(/%\d{0}/g, '%25');	
	sText = sText.replace(/\+/g, '%2B');		
	sText = sText.replace(/&amp;/g, '%26');
	sText = sText.replace(/&\w{0}#{0}/g, '%26');
	sText = sText.replace(/\"/g, '%22');
	sText = sText.replace(/\#/g, '%23');

    return sText;
}

// This function converts CSS rgb(x, x, x) to hexadecimal
function rgb2Hex(rgbColour) {
  try{
    // Remove rgb()
    var rgbValues = rgbColour.substring(rgbColour.indexOf("(")+1, rgbColour.indexOf(")"));
    // Split RGB into array
    var rgbArray = rgbValues.split(", ");

    // Get RGB values
    var red   = parseInt(rgbArray[0]);
    var green = parseInt(rgbArray[1]);
    var blue  = parseInt(rgbArray[2]);
    var alpha  = parseInt(rgbArray[3]);
    if (alpha == 0)
        return;
    // Build hex colour code
    var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue);
  }
  catch(e){
    alert(e);
    //alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex");
  }

  return hexColour;
}

/*
Converts a number to hexadecimal format
*/
function IntToHex(strNum) {
  base = strNum / 16;
  rem = strNum % 16;
  base = base - (rem / 16);
  baseS = MakeHex(base);
  remS = MakeHex(rem);
  return baseS + '' + remS;
}


/*
gets the hex bits of a number
*/
function MakeHex(x) {
  if((x >= 0) && (x <= 9))
  {
    return x;
  }
  else
  {
    switch(x)
    {
      case 10: return "A";
      case 11: return "B";
      case 12: return "C";
      case 13: return "D";
      case 14: return "E";
      case 15: return "F";
    }
  }
}
