//***************** APPLICATION VALUES **************************
var pluginTable = new Array(); // Plugin table
// Include plugin
document.write('<script type="text/javascript" src="http://www.google.com/jsapi"></script>');

document.write('<script type="text/javascript" src="'+
				$("#JSPath").val()+'use/widgetmaker_html.js"></script>');
document.write('<script type="text/javascript" src="'+
				$("#JSPath").val()+'use/widgetmaker_blogger.js"></script>');			
//******************** FLASH VALUES ***************************** 
var FSplayer = $("#swfPath").val()+"FSPlayer.swf";
var fileJQuery = $("#JSPath").val()+"jquery.js"; // The jquery library
var fontURL = $("#fontListURL").val();
var fontStorageURLOverride = $("#fontStorageURLOverride").val();
var maxWidth = "100%"; // The maximum width
var maxHeight = "100%"; // The maximum height
var theHeight; // The current height
var customWidthMax = 900; // The max custom width
var customWidthMin = 200; // The min custom width
var fontKey; // Current font used
var fontKeylist; // holding the final list of font keys
var flashBackgroundColor = "0xFFFFFF"; // Background color

var signedKey = {"privateFont":
                    {"key":"","signed":false},
                 "pp":
                    {"key":"","signed":false},
                };
//******************** TEXT VALUES *****************************
var flagFirstWriting = true; // Flag for the fist writing
var textWidget; // Text
var ieSelection; // The selectionned text (FOR IE)
//************************** TIMER *****************************
var timer;
var waitingTime = 500;
//******************** FONT VALUES *****************************
var defaultFontSize = 30;
var nbColFont = 4; // Nb of colums in the fonts list
var defaultFont = 'Super_P';
// The minimum font's size
var fontSizeMin = 18;
// The madium font's size
var fontSizeMedium = 40;
// The maximum font's size
var fontSizeMax = 50;
// Font size
var fontSize;
//**************************************************************
/***************************************
* Name : init
* Goal : Initialize the application
****************************************/
window.onload = function init(){
	
	$("#txtMessage").attr("disabled", "disabled");
	// Add the plugin
	addPlugin();
	// Initialize the plugin selector
	fillKindResult();
	// Initialize the target selector
	changeKindResult();
	// Initialize the font size
	fillSelectFontSize();	
	// Clear the area
	clearArea();		
	// Call the fontmenu
    getFontList();
	// enable the text box
	$("#txtMessage").removeAttr("disabled");  
}
function getFontList(){
   $.getJSON(fontURL,makeFontMenu);
}
/***************************************
* Name : addPlugin
* Goal : add every plugins
****************************************/
function addPlugin() {	
	// Prepare the value
	sharer = new Html();
	// Add the value into the table 
	pluginTable.push(sharer);
	// Prepare the value
	sharer = new Blogger();	
	// Add the value into the table
	pluginTable.push(sharer);
}
/***************************************
* Name : fillKindResult
* Goal : Initialize the plugin selector
****************************************/
function fillKindResult() {	
	// Reinitialize the selectShare
	$("#kindOfResult").html("");		

	// Range the table
	for (i = 0; i < pluginTable.length; i++){
		// If we display all the width choice into the main select
		if(i == 0){
			
			$("#kindOfResult").html($("#kindOfResult").html() +
				'<label><input type="radio" name="grbKindResult" onClick="changeKindResult();" value="'+i+
				'" checked="checked"/><span>'+ pluginTable[i].name +'</span></label><br/><br/>');	
		}
		else{
			$("#kindOfResult").html($("#kindOfResult").html() +
				'<label><input type="radio" name="grbKindResult"onClick="changeKindResult();" value="'+i+
				'" /><span style="margin-right:15px;">'+ pluginTable[i].name +'</span></label>');		
		}			
	}
}
/***************************************
* Name : makeFontMenu
* Goal : Initialize the font menu
****************************************/
function makeFontMenu(jsonFile) { 
    
    /***************************************
    * Name : createFontListItem
    * Goal : Create a font list item (td) and
    *        create a new line if this is the
    *        last of the current line
    * Params : 
    *   - font the font object
    *   - the current position in the table
    * Return : the font list item
    ****************************************/
    function createFontListItem(font,id){    
        var fontItem = '';        
        // If we begin a line
        if (id % nbColFont == 0){
            fontItem +=  '<tr>';
        }  
        // Add the font in the table
        fontItem +=   '<td class="font" onclick="changeFont(\''+font.preview+'\',\''+font.key+'\');hideFontMenu();renderWidget(\'auto\');return false;"><img src="'+font.preview+'"/></td>';			
        // End of line
        if( (id+1) % nbColFont == 0){
            fontItem +=  '</tr>';	
        }        
        return fontItem;
    }
    
    // Create the font array
    var fonts = jsonFile.fonts;
    var privateFont = new Array();
    var publicFont = new Array(); 
    
    // Split private/public font
    for (i = 0; i < fonts.length;i++){
        if(fonts[i].type == 'private'){
            privateFont.push(fonts[i]);
        }
        else if(fonts[i].type == 'public'){
            publicFont.push(fonts[i]);
        }
    }    
	// Create the table
	var fontList = '<table onclick="return false;">';	
	// To browse the table
	var j = 0;    
    //********************************
    // PRIVATE FONTS
    //********************************  
	// For each font
	for (i = 0; i < privateFont.length;i++){
        if(privateFont[i].preview){        
            // If this is the default font
            if(j == 0 || privateFont[i].name == defaultFont){
                changeFont(privateFont[i].preview,privateFont[i].key);
            }            
            fontList += createFontListItem(privateFont[i],j);
            j++;
        }
	}    
    //********************************
    // PUBLIC FONTS
    //********************************
    // For each font
    for (i = 0; i < publicFont.length;i++){
        if(publicFont[i].preview){         
            // If this is the default font
            if(($("#userAuthenticated").val() != 1 && i == 0) || publicFont[i].name == defaultFont){
                changeFont(publicFont[i].preview,publicFont[i].key);
            }            
            fontList += createFontListItem(publicFont[i],j);
            j++;
        }
    }    
	// Finish the table's line
	if(j%nbColFont!= 0){
		while(j%nbColFont != 0){
			fontList +=  '<td></td>';
			j++;
		}
		fontList +=  '</tr>';
	}
	// Finish the table		
	fontList+='</table>';		

	// Put the table on the html page
	document.getElementById("tabFontFS").innerHTML = fontList;
	
} 
/***************************************
* Name : getRandomDivID
* Goal : Return a random div id
****************************************/
function getRandomDivID(){
	var d = new Date();
	var timestamp = d.getTime();
	var random = Math.floor(Math.random()*1000000);
	return 'Fontself'+timestamp+random;
}
/***************************************
* Name : changeSelectSize
* Goal : When the width size change
****************************************/
function changeSelectSize() {

	$("#resultTitle").css("display","none");
	$("#resultArea").css("display","none");
	$("#errorMessages").css("display","none");
	$("#pluginForm").html("");	
	// If the user doesn't want to create a new size
	if(document.getElementById("selectSize").value != "other"){
		this.maxHeight = pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].size[document.getElementById("selectSize").selectedIndex][2];
	
	}
	else{
		$("#txtNewWidth").val("");
		$("#backgroundLinkPopUp").css("display","block");
		$("#boxNewWidthPopUp").css("display","block");
		$("#boxNewWidthPopUp").css("left","50%");
		$("#boxNewWidthPopUp").css("top","250px");
	}
}
/***************************************
* Name : changeKindResult
* Goal : Initialize, display or hide the 
         select width size / target
****************************************/
function changeKindResult(){
	// Hide the result area
	$("#resultTitle").css("display","none");
	$("#resultArea").css("display","none");
	$("#errorMessages").css("display","none");
	// Reinitialize the selectSize
	$("#selectSize").html("");	
	// Get the size table
	var size = pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].size;	
	// Range the table
	for (i = 0; i < size.length; i++){
		if(i == 0)	
			$("#selectSize").html($("#selectSize").html()+'<option maxHeight="'+size[i][2]+'" value="'+ size[i][1] +'" selected="selected">'+ size[i][0] +'</option>');	
		else		
			$("#selectSize").html($("#selectSize").html() + '<option maxHeight="'+size[i][2]+'" value="'+ size[i][1] +'">'+ size[i][0] +'</option>');					
	}
	// If the plugin allowed new size
	if(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].allowedNewSize)
		$("#selectSize").html($("#selectSize").html() + '<option value="other">Other size...</option>');
	
	
	$("#selectText").html(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].typeChoice + ' :');
	
	// If the plugin want to display the different choice
	if(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].displayPluginChoice){
		$("#widgetSize").css("display","block");
	}
	else{
		$("#widgetSize").css("display","none");
	}  
	changeSelectSize();
}

/***************************************
* Name : fillSelectFontSize
* Goal : Initialize the font size 
         select box
****************************************/
function fillSelectFontSize(){
	$("#selectFontSize").html("");
	var fontSize = fontSizeMin;
	while(fontSize<=fontSizeMax){
		if(fontSize != defaultFontSize)
			$("#selectFontSize").html($("#selectFontSize").html()+'<option value="'+ fontSize +'">'+ fontSize +'</option>');
		else
			$("#selectFontSize").html($("#selectFontSize").html()+'<option value="'+ fontSize +'" selected="selected">'+ fontSize +'</option>');
			
		if (fontSize >= fontSizeMin && fontSize < fontSizeMedium)
			fontSize += 2;
		else if (fontSize >= fontSizeMedium && fontSize <= fontSizeMax)
			fontSize += 5;
	}
}
/***************************************
* Name : renderWidget
* Goal : Render the widget
* Param : 
*	mode => if the widget is rendered auto
****************************************/
function renderWidget(mode){
	
	// Hide the result zone
	$("#pluginShareButton").css("display","none");
	$("#resultAreaPreview").css("display","none")
	$("#resultArea").css("display","none");
	$("#resultTitle").css("display","none");
	$("#resultAreaText").css("display","none");
	
	//Check the text
	if($("#txtMessage").val() == "" || flagFirstWriting) {
		if(mode != "auto")
			alert("Your message can't be empty!");
		return false;
	}
	// Show the preview
	$("#resultTitle").css("display","block");
	$("#resultArea").css("display","block");
    
    // Initialize the key signature checker
	signedKey.privateFont.signed = false;
    signedKey.pp.signed = false;
    
    // Sign the message if the user is logged in
	if ($("#userAuthenticated").val()==1) {
		
        // If the key is private
        if(fontKey.charAt(0) != '_'){
            signedKey.privateFont.key = fontKey;
        }
        else{
            signedKey.privateFont.signed = true; // We don't need to signed public keys
        }
        // Sign the pp
        signPPKey($("#txtMessage").val(),ppKeySigned);
        
	} else {
        // Both of the key don't need to be signed
        signedKey.privateFont.signed = true;
        signedKey.pp.signed = true;
		displayFlashRender();
	}
}
function fontKeySigned(privateFontKey){
    signedKey.privateFont.signed = true;
    signedKey.privateFont.key = privateFontKey;    
    displayFlashRender();
}
function ppKeySigned(personalFontKey){
    signedKey.pp.signed = true;
    signedKey.pp.key = personalFontKey;
    
    // If we need to sign the private key
    if(!signedKey.privateFont.signed){
        signKey(encodeURIComponent($("#txtMessage").val()),signedKey.privateFont.key,fontKeySigned);
    }
    else{    
        displayFlashRender();
    }
}
/***************************************
* Name : displayFlashRender
* Goal : display the FSplayer with the right font keys (pp+font)
****************************************/
function displayFlashRender() {

    if(signedKey.pp.key != ""){
        fontKeylist = signedKey.pp.key+',';
    }
    else{
        fontKeylist = "";
    }

    // If the font key is private
    if(fontKey.charAt(0) != '_'){
        if(signedKey.privateFont.key != ""){
            fontKeylist += signedKey.privateFont.key;
        }
    }
    else{
        fontKeylist += fontKey;
    }
    
    // Create the font list
	fontKeylist = signedKey.pp.key+','+fontKey;
    
	// Get the width
	maxWidth = $("#selectSize").val();	
	var tempMaxWidth = maxWidth;
	
	// If the user want a static FSPlayer (without JS) we have to remove the scroll bar width
	if(maxWidth != "100%"){
		tempMaxWidth = parseInt(tempMaxWidth)-10;
	}
	// Get the text
	textWidget = encodeURIComponent($("#txtMessage").val());
	// Get the font size
	fontSize = $("#selectFontSize").val();
	
	// Display the result preview area
	$("#resultAreaPreview").css("display","block");
	// If the plugin use Google Analitycs
	if(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].useGA){
		pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].googleAnalytics(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].size[document.getElementById("selectSize").selectedIndex][0]);
	}	
	
	// Initialize the flashvars
	var flashVars = new Array(); 	
	flashVars['fkey'] = fontKeylist;
	flashVars['size'] = fontSize;
	flashVars['divId'] = "fontselfSWF";
	flashVars['text'] = textWidget;
	flashVars['bgColor'] = flashBackgroundColor;
	
	
	
	
	// If the fontStorageURLOverride is set, we add the flashvar
	if(fontStorageURLOverride != "" ){
		flashVars['fontStorageURLOverride'] = fontStorageURLOverride;
		// Add moderation flashvars
		flashVars['moderationDomain']="test";
		flashVars['urlOverride']="http://test.fontself.com";
	}
	// Initialize the flash params
	var params = {
		play: true,
		loop: false,
		quality: "best",
		wmode: "transparent",
		allowScriptAccess: "always",
		allowfullscreen: false,
		style:"border:solid 1px;"
	};
	// Initialize the attributes
	var attributes = { id: "fontselfSWF" };
	// Create the swf object
	swfobject.embedSWF(	FSplayer, "fontselfSWF",
						tempMaxWidth, "18px", "10.0.0", false, flashVars, params, attributes);	
	
}	
/***************************************
* Name : setFlashHeight
* Goal : Resize the FSplayer and call the
*		 displayResults function
*		 This function is called by the 
*		flash object
* Param : 
*	o => the flash object
****************************************/
function setFlashHeight(o){
	// Get the height
	theHeight = o.h;
	clearTimeout(timer);
	timer = setTimeout('resizeFlash("'+o.id+'")',waitingTime);	
}
function resizeFlash(id){
	// Resize the player containers
	$("#previewSWF").height(theHeight + "px");
	$("#" + id).height(theHeight + "px");	
	if(maxWidth == "100%"){
		$("#" + id).width(maxWidth);
		$("#previewSWF").width(maxWidth);		
	}
	else{
		$("#" + id).width(maxWidth+"px");
		$("#previewSWF").width(maxWidth+"px");
	}	
	displayResults();
}
/***************************************
* Name : displayResults
* Goal : Display the results in the 
		 application
****************************************/
function displayResults(){	

	// If the plugin want to display something into the result text area
	if(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].displayResultAreaText) {	
		// Display the text result area 
		$("#resultAreaText").css("display","block");	
		// Get the tool box html
		$("#resultTextBox").val(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].getResultText());		
		// Fill the html result
		$("#toolBarResultText").html('<div style="text-align: right;">'+
			pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].getToolBox()+'</div>');
	}	 
	
	// Display the error message if the height is bigger than the max height size
	if(maxHeight != "100%" && maxHeight < theHeight){
		$("#errorMessagesText").html(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].size[document.getElementById("selectSize").selectedIndex][3]);
		$("#errorMessages").css("display","block");
	}
	else{
		$("#errorMessages").css("display","none");
	}
	// If the plugin want to display something into the plugin button area
	if(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].displayPluginButton) {		
		// Get the button
		$("#pluginShareButton").html(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].getPluginShareButton());
		// Display the button plugin area 
		$("#pluginShareButton").css("display","block");
	}
	
	// If the plugin want to display something into the plugin button area
	if(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].displayPluginForm) {
	
		// if the zone param exist
		if(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].size[document.getElementById("selectSize").selectedIndex][4]) {
			// "display" the form for this specific zone
			$("#pluginForm").html(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].getPluginForm(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].size[document.getElementById("selectSize").selectedIndex][4]));
		}
		else {
			// "display" the form
			$("#pluginForm").html(pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].getPluginForm());
		}
	}
}
/***************************************
* Name : changeFont
* Goal : Change the current font
* Param : 
*	fontPreview => the font image
*	fontKeypar  => the font key (id)
****************************************/
function changeFont(fontPreview,fontKeypar){			
	$("#fontFS").html('<img src="'+fontPreview+'"/>');
	fontKey = fontKeypar;
}
/***************************************
* Name : getSelection
* Goal : return the selectionned text
****************************************/
function getSelection(){
	var textarea = $("#txtMessage").get(0);
	// Code for IE
	if (document.selection){	
		document.getElementById("txtMessage").focus();
		this.ieSelection = document.selection.createRange(); 
		return ieSelection.text;		
	}
	// Code for Mozilla
	var start = textarea.selectionStart;
	var end = textarea.selectionEnd;
	return textarea.value.substring(start, end);
}
/***************************************
* Name : addTag
* Goal : Add a tag
* Param : 
*	tag => the tag
*	name  => the tag name (for GA)
****************************************/
function addTag(tag, name){	
	var textarea = $("#txtMessage").get(0);
	// Code for IE
	if (document.selection){
		document.getElementById("txtMessage").focus();
		var sel = document.selection.createRange();
		// Finally replace the value of the selected text with this new replacement one
		sel.text = '['+tag+']' + sel.text + '[/'+tag+']';
		return;
	}
	// Code for Mozilla
	var len = textarea.value.length;
	var start = textarea.selectionStart;
	var end = textarea.selectionEnd;
	var sel = textarea.value.substring(start, end);
	var replace = '['+tag+']' + sel + '[/'+tag+']';
	// Replace the selected text with the new one
	textarea.value = textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);
	
	// Select the new text
	textarea.select(start,end);
	textarea.selectionStart = start;
	textarea.selectionEnd = start+replace.length;
	
	//Track on GA
	if(name && typeof pageTracker != "undefined"){
		pageTracker._trackEvent('Widget Maker', 'add tag', name);	
	}	
}
/***************************************
* Name : openLinkPopUp
* Goal : Open and initilize the pop up
****************************************/
function openLinkPopUp(){
	$("#backgroundLinkPopUp").css("display","block");
	$("#boxLinkPopUp").css("display","block");
	$("#txtURLLink").val("http://");
	$("#txtDescriptionLink").val(getSelection());
}
/***************************************
* Name : openLinkPopUp
* Goal : Close the pop up
****************************************/
function closeLinkPopUp(){
	$("#backgroundLinkPopUp").css("display","none");
	$("#boxLinkPopUp").css("display","none");
}
/***************************************
* Name : closeNewWidthPopUp
* Goal : Close the new width pop up
****************************************/
function closeNewWidthPopUp(){
	$("#backgroundLinkPopUp").css("display","none");
	$("#boxNewWidthPopUp").css("display","none");
	$("#selectSize").attr("selectedIndex",pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].size.length-1);
}
/***************************************
* Name : addNewWidth
* Goal : Add a new width in the table
****************************************/
function addNewWidth(){

	var objRegExp  = /(^\d\d*$)/;
	var currentWidth = $("#txtNewWidth").val();
	// If it's an integer
	if(	objRegExp.test(currentWidth) && 
		currentWidth <= customWidthMax &&
		currentWidth >= customWidthMin){
		
		// Add the new width into the plugin size
		pluginTable[$('input[type=radio][name=grbKindResult]:checked').attr('value')].size.push([currentWidth+' px',currentWidth,"100%"]);
		// Refresh the select box
		changeKindResult();
		closeNewWidthPopUp();
		changeSelectSize();
	}
	else
		alert('Warning : your width size must be an integer between '+ customWidthMin + ' and '+ customWidthMax+' px!');
}
/***************************************
* Name : openImagePopUp
* Goal : Open and initilize the img pop up
****************************************/
function openImagePopUp(){
	$("#backgroundLinkPopUp").css("display","block");
	$("#boxImagePopUp").css("display","block");
	$("#txtURLImage").val("http://");
}
/***************************************
* Name : closeImagePopUp
* Goal : Close the img pop up
****************************************/
function closeImagePopUp(){
	$("#backgroundLinkPopUp").css("display","none");
	$("#boxImagePopUp").css("display","none");
}
/***************************************
* Name : addImgLink
* Goal : Add the image link into the text
****************************************/
function addImgLink(){
	// The text box isn't empty
	if($("#txtURLImage").val() == ""){
		alert("Please enter a link!");
		return false;
	}
	
	// Check the URL syntaxe
	var urlRegxp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	if (!urlRegxp.test($("#txtURLImage").val())){
		alert("The URL syntaxe isn't right!");
		return false;
	}
	
	
	var textarea = document.getElementById("txtMessage");	
	// Code for IE
	if (ieSelection){	
		// Finally replace the value of the selected text with this new replacement one
		this.ieSelection.text = '[img]' + $("#txtURLImage").val() + '[/img]';
		closeLinkPopUp();
		return;
	}
	// code for Mozilla
	var len = textarea.value.length;
	var start = textarea.selectionStart;
	var end = textarea.selectionEnd;
	var sel = textarea.value.substring(start, end);
	var replace = '[img]' + $("#txtURLImage").val() + '[/img]';
	// Here we are replacing the selected text with this one
	textarea.value = textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);
	
	// Select the new text
	textarea.select(start,end);
	textarea.selectionStart = start;
	textarea.selectionEnd = start+replace.length;
	
	//Track on GA
	if (typeof pageTracker != "undefined") 
		pageTracker._trackEvent('Widget Maker', 'add tag', 'image');	
	
	// Close the pop up
	closeImagePopUp();

}
/***************************************
* Name : clearArea
* Goal : Clear the text area
****************************************/
function clearArea(){
	$("#txtMessage").val("Type your text here!");
	flagFirstWriting = true;
	renderWidget("auto");
}
/***************************************
* Name : clickArea
* Goal : Clear the first text
****************************************/
function clickArea(){
	if(flagFirstWriting){
		$("#txtMessage").val("");
		flagFirstWriting = false;
	}
}
/***************************************
* Name : quitArea
* Goal : Add "type your text" if the user
		leave the text area
****************************************/
function quitArea(){
	if($("#txtMessage").val() == ""){
		$("#txtMessage").val("Type your text here!");
		flagFirstWriting = true;
	}

}
/***************************************
* Name : addLink
* Goal : Add the link tag
****************************************/
function addLink(){
	// The both text box aren't empty
	if($("#txtDescriptionLink").val() == "" || $("#txtURLLink").val() == ""){
		alert("Please enter a link and a description!");
		return false;
	}
	
	// Check the URL syntaxe
	var urlRegxp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	if (!urlRegxp.test($("#txtURLLink").val())){
		alert("The URL syntaxe isn't right!");
		return false;
	}
	
	
	var textarea = document.getElementById("txtMessage");	
	// Code for IE
	if (ieSelection){	
		// Finally replace the value of the selected text with this new replacement one
		this.ieSelection.text = '[url='+$("#txtURLLink").val()+']' + $("#txtDescriptionLink").val() + '[/url]';
		closeLinkPopUp();
		return;
	}
	// code for Mozilla
	var len = textarea.value.length;
	var start = textarea.selectionStart;
	var end = textarea.selectionEnd;
	var sel = textarea.value.substring(start, end);
	var replace = '[url='+$("#txtURLLink").val()+']' + $("#txtDescriptionLink").val() + '[/url]';
	// Here we are replacing the selected text with this one
	textarea.value = textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);
	
	// Select the new text
	textarea.select(start,end);
	textarea.selectionStart = start;
	textarea.selectionEnd = start+replace.length;
	
	// Track on GA
	if (typeof pageTracker != "undefined") 
		pageTracker._trackEvent('Widget Maker', 'add tag', 'url');	
	
	// Close the pop up
	closeLinkPopUp();
}
/***************************************
* Name : displayFontMenu
* Goal : Display the font menu
****************************************/
function displayFontMenu(){
	$("#tabFontFS").css("display","block");
}
/***************************************
* Name : hideFontMenu
* Goal : Hide the font menu
****************************************/
function hideFontMenu(){
	$("#tabFontFS").css("display","none");
}
/***************************************
* Name : openHelpWindow
* Goal : Open the help windows
****************************************/
function openHelpWindow(){
	window.open("http://help.fontself.com/apps/widget-maker?template=largeapplicationhelptemplate",'','height=750,width=1100,resizable=yes,scrollbars=yes,toolbar=yes,status=yes');
}
/***************************************
* Name : getSwfPostText
* Goal : return the my
* Param : 
*	modeJS => if we add the JS
****************************************/
function getSwfPostText(modeJS,referrer){
	var postText = "";
	var givenText = textWidget.replace(/\'/g,'%27');
	if (referrer){
		referrer = 'altReferrer='+referrer+'&amp;';
	}
	if(modeJS){
			postText = 	'<script language=\'javascript\' src=\''+fileJQuery+'\'></script>'+
							'<script>'+
								'function setFlashHeight(o) {'+
									'var e = jQuery(\'#\' + o.id);'+
									'e.height(o.h + \'px\');'+
									'e.width(\'100%\');'+
									'jQuery(\'#\' + o.id+\'_embed\').height(o.h + \'px\');'+
								'}'+
							'</script>';
			
			var divID = getRandomDivID();
			postText+='<object id=\''+divID+'\' width=\'100%\' height=\'18px\' pluginspage=\'http://www.adobe.com/go/getflashplayer\'>'+
							'<param name=\'allowFullScreen\' value=\'true\'></param>'+
							'<param name=\'wmode\' value=\'transparent\'></param>'+
							'<param name=\'quality\' value=\'best\'></param>'+
							'<param name=\'allowScriptAccess\' value=\'always\'></param>'+
							'<param name=\'allownetworking\' value=\'always\'></param>'+
							'<embed id=\''+divID+'_embed\' height=\'18px\' src=\''+FSplayer+'\' type=\'application/x-shockwave-flash\'  quality=\'best\''+
							'allowscriptaccess=\'always\' allownetworking=\'always\' allowfullscreen=\'true\' width=\'100%\' height=\'100%\' '+
							'flashvars=\'fkey='+fontKeylist+'&amp;size='+
							fontSize+'&amp;'+referrer+'bgColor='+flashBackgroundColor+
							'&amp;divId='+divID+'&amp;';	
			// If the fontStorageURLOverride is set, we add the flashvar
			if($("#fontStorageURLOverride").val() != "" ){
				postText+=	'fontStorageURLOverride='+$("#fontStorageURLOverride").val()+'&amp;';
			}
			
			postText+=		'text='+givenText+'\'>'+
							'</embed></object>';
	}
	else{
		postText = '<object pluginspage=\'http://www.adobe.com/go/getflashplayer\'>'+
					'<param name=\'allowFullScreen\' value=\'true\'></param>'+
					'<param name=\'wmode\' value=\'transparent\'></param>'+
					'<param name=\'quality\' value=\'best\'></param>'+
					'<param name=\'height\' value=\''+theHeight+'\'></param>'+
					'<param name=\'allowScriptAccess\' value=\'never\'></param>'+
					'<param name=\'allownetworking\' value=\'always\'></param>'+
					'<embed src=\''+FSplayer+'\' type=\'application/x-shockwave-flash\' '+
					'allowscriptaccess=\'never\' quality=\'best\' allownetworking=\'always\' allowfullscreen=\'true\' width=\''+
					 maxWidth+'\' height=\''+theHeight+'\' '+
					'flashvars=\'fkey='+fontKeylist+'&amp;'+referrer+'size='+fontSize+'&amp;bgColor='+
					flashBackgroundColor+'&amp;';
		// If the fontStorageURLOverride is set, we add the flashvar
		if($("#fontStorageURLOverride").val() != "" ){
			postText+=	'fontStorageURLOverride='+$("#fontStorageURLOverride").val()+'&amp;';
		}
		
		postText+=	'text='+givenText+'\'>'+
					'</embed></object>';
	
	}
	return postText;
}
/***************************************
* Name : getTextWithoutTag
* Goal : return the bb code in html
****************************************/
function getTextWithoutTag(){
	var txt = $("#txtMessage").val();
	alert(code_to_html(txt));
}
 
