/**
 * @author Michael.Howlett
 * @amends Oliver D'Alton 
 * 
 */

 
 
 $(document).ready(function(){ 
//get difr-cache xml
 var difrCacheXml;
 difrCacheXml = fnLoadXml("/_config/difr-cache.xml");

	$('.difr').each(
		
		function(){
			
			var textcontent = $(this).text();
			var htmlcontent = $(this).html();
			var item = $(this);
			
				
			// settings from css
			var fontSize = $(this).css("font-size");
			fontSize = fontSize.substring(0, (fontSize.length -2));
			
			var font = $(this).css("font-family");
			
			var colour = $(this).css("color");
			
			if(!$.browser.msie){
			    colour = rgbToHex(colour);
			}
			colour = colour.substring(1, colour.length);
			
			var kerning = 5
			if(($(this).css("letter-spacing") != "normal")){
				kerning = $(this).css("letter-spacing");
				kerning = parseFloat(kerning.substring(0, (kerning.length -2)));
			}

			if( $(this).css("text-transform") == "uppercase"){
				    textcontent = textcontent.toUpperCase();
			}


			// load the image
		   	var image = new Image();
	
			// once loaded - format the image
			runOnLoad(function(){
			    var halfHeight = parseFloat(image.height) / 2;
				$(item).css({width: image.width, height: halfHeight});
			});
			
			/* changed the method of generating the images and the the css refs, difr now saves images to the set difr folder and the 
			image is referenced for readability and seo. Added rollover options to the difr system so that you can create the rollover states also
	        if you use this you just need to set the difr anchors CSS to realign the backround to suit, on hover, you must send the difr webhandler
	        a value of isRlOvr=true and a hex colour code of hovcolr=<hexcolourcode> *with no hash; also you must change the height of your container
            to half the height of the image generated for the rollover to work - Oliver
            
            Added xml cache list generated by the difr service, so now the xml cache is checked for existing files and the difr service should only ever
            be called once to create the image and then never again. -Oliver
            
            TODO: add a cleanup function for the cache.
  
         
	        */
	         
            var text = textcontent;
            var sFileName = fnCompressString(text + fontSize + colour + kerning);
            var bImgCached = false;
            var iCImgW = 0;
            var iCImgH = 0;
            
            $(difrCacheXml).find("image").each(function(){
                if($(this).attr("file") == sFileName+".gif"){
                    iCImgW = parseFloat($(this).attr("w"));
                    iCImgH = parseFloat($(this).attr("h"));
                    bImgCached = true;
                }
            });
            
           if(bImgCached){
                image.src  = "/images/difr/" + sFileName +".gif";
                image.width = iCImgW;
                image.height = iCImgH;
            }else{
                //service call for the difr system. edit to change settings.
               image.src =  "/services/fontImageReplace.ashx?text=" + escape(textcontent) + "&font=../fonts/" + font + ".ttf&size=" + fontSize + "&colour="+ colour + "&kerning="+ kerning + "&isRlOvr=true&hovcolr=110C2A&useGif=true";  
            }
			
			$(this).css("background", "transparent  url("+image.src+") no-repeat scroll top left");
		}
	);
	

	
	function rgbToHex(rgb) {
		var rgbvals = /rgb\((.+),(.+),(.+)\)/i.exec(rgb);
		var rval = parseInt(rgbvals[1]);
		var gval = parseInt(rgbvals[2]);
		var bval = parseInt(rgbvals[3]);
		
		return '#' + (	getRGBzeros(rval.toString(16)) +	getRGBzeros(gval.toString(16)) +	getRGBzeros(bval.toString(16))	).toUpperCase();
	
	} 

	function getRGBzeros(sColourVal){
	if(sColourVal.length < 2){
	    sColourVal = "0"+sColourVal;
	    }
	return sColourVal;
	}

});

function fnLoadXml(sURL){
    var xResponse = $.ajax({
				type: "GET",
				url: sURL,
				dataType: "xml",
				async: false
			});
    return xResponse.responseXML;
}

function fnCompressString(strIn){

//was using hashing, found it was overkill - oliver

    strIn = removeAll(strIn," ");
    strIn = removeAll(strIn,".");
    strIn = removeAll(strIn,":");
    strIn = removeAll(strIn,"&copy;");
    strIn = removeAll(strIn,";");
    strIn = removeAll(strIn,"#");
    strIn = removeAll(strIn,"?");
    strIn = removeAll(strIn,"%20");
    strIn = removeAll(strIn,"©");
    strIn = removeAll(strIn,"&");
    strIn = removeAll(strIn,",");
    
    return strIn;    
}

function removeAll(strIn, reStr){
    var strReturn = "";
    strArr = strIn.split(reStr);
    for(var i = 0;i<strArr.length;i++)
    {
       strReturn = strReturn + strArr[i].replace(reStr,"");
    }
    return strReturn;
}

function ascii_value (c)
{
	// restrict input to a single character
	c = c . charAt (0);

	// loop through all possible ASCII values
	var i;
	for (i = 0; i < 256; ++ i)
	{
		// convert i into a 2-digit hex string
		var h = i . toString (16);
		if (h . length == 1)
			h = "0" + h;

		// insert a % character into the string
		h = "%" + h;

		// determine the character represented by the escape code
		h = unescape (h);

		// if the characters match, we've found the ASCII value
		if (h == c)
			break;
	}
	return i;
}