function ElemAdd()
{
	  var ndx = parseInt(document.getElementById("divNum").value);
	  var div = document.createElement("div");
	  div.id = "divMap" + ndx;
	  div.setAttribute("class","ui-widget-content");
	  div.setAttribute("href","http://");
	  div.innerHTML = '&nbsp;&nbsp;<a href=\'javascript:void(0)\' onclick=\'HrefSet("divMap'+ndx+'")\' style="color:#0000FF">Link</a> | <a href=\'javascript:void(0)\' onclick=\'ElemRemove("divMap'+ndx+'")\' style="color:#0000FF">Remove</a>';
	  document.getElementById("bgimgdiv").appendChild(div);
	  $("#divMap" + ndx).resizable();
	  $("#divMap" + ndx).draggable({ containment: 'parent' });
      document.getElementById("divMap" + ndx).style.position = "absolute";
      document.getElementById("divMap" + ndx).style.left = "25px";
      document.getElementById("divMap" + ndx).style.top = (25 + parseInt(document.getElementById("divNum").value)*4) + "px";
      document.getElementById("divMap" + ndx).style.padding = "0px";
      document.getElementById("divMap" + ndx).style.zIndex = "99999";
      document.getElementById("divMap" + ndx).style.width = "150px"; 
      document.getElementById("divMap" + ndx).style.height = "30px";
      document.getElementById("divMap" + ndx).style.border = "solid 2px #cccccc";
      document.getElementById("divMap" + ndx).style.backgroundColor = "#808080";
      document.getElementById("divMap" + ndx).style.filter = "alpha(opacity=75)";		  
      document.getElementById("divMap" + ndx).style.opacity = ".75";		  
	  ndx = ndx + 1;
	  document.getElementById("divNum").value = ndx;
	  return div;
}

function TextElemAdd()
{
	  var ndx = parseInt(document.getElementById("notesNum").value);
	  var div = document.createElement("div");
	  div.id = "divNote" + ndx;
	  //div.setAttribute("class","ui-widget-content");
	  div.innerHTML = '<div style="background-color:#CCCCCC"><a href=\'javascript:void(0)\' onclick=\'TextSet("txtNote'+ndx+'")\' style="color:#0000FF">Text</a> | <a href=\'javascript:void(0)\' onclick=\'ElemRemove("divNote'+ndx+'")\' style="color:#0000FF">Remove</a></div><div id="txtNote' + ndx + '" class="txtnote"></div>';
	  document.getElementById("bgimgdiv").appendChild(div);
	  $("#divNote" + ndx).resizable();
	  $("#divNote" + ndx).draggable({ containment: 'parent' });
      document.getElementById("divNote" + ndx).style.position = "absolute";
      document.getElementById("divNote" + ndx).style.left = "25px";
      document.getElementById("divNote" + ndx).style.top = (25 + parseInt(ndx)*4) + "px";
      document.getElementById("divNote" + ndx).style.padding = "0px";
      document.getElementById("divNote" + ndx).style.zIndex = "99999";
      document.getElementById("divNote" + ndx).style.width = "150px"; 
      document.getElementById("divNote" + ndx).style.height = "100px";
      document.getElementById("divNote" + ndx).style.border = "solid 2px #cccccc";
      document.getElementById("divNote" + ndx).style.backgroundColor = "transparent";
	  ndx = ndx + 1;
	  document.getElementById("notesNum").value = ndx;
	  return div;
}



function TextSet(id)
{
    var div = document.getElementById(id);
	document.getElementById("hrefDivId").value = id;
	document.getElementById("txtSetText").value = div.innerHTML;
	var color;
	var fontFamily;
	var fontSize;
	if(div.style.fontFamily)
	{
	    fontFamily = div.style.fontFamily;
	}
	else
	{
	    fontFamily = "Tahoma";
	}
	if(div.style.fontSize)
	{
	    fontSize = div.style.fontSize;
	}
	else
	{
	    fontSize = "12px";
	}
	if(div.getAttribute("color"))
	{
	    color = div.getAttribute("color");
	}
	else
	{
	    color = "#000000";
	}
    document.getElementById("font_color").value = color;
    document.getElementById("font_colorShow").style.backgroundColor = HexToRGB(color);	    
    document.getElementById("font_family").value = fontFamily;	
    document.getElementById("font_size").value = fontSize;	
    $("#textSet").dialog({
        autoOpen: false,
        bgiframe: true,
        height: 525,
        width: 450,
        title: 'Text',
        modal: false,
        buttons: {
	        Ok: function() {
	            document.getElementById(document.getElementById("hrefDivId").value).innerHTML = $("#txtSetText").val();
	            color = document.getElementById("font_color").value;
	            fontFamily = document.getElementById("font_family").options[document.getElementById("font_family").selectedIndex].value;
	            fontSize = document.getElementById("font_size").options[document.getElementById("font_size").selectedIndex].value;
	            if(color)
	            {
	                document.getElementById(document.getElementById("hrefDivId").value).style.color = document.getElementById("font_colorShow").style.backgroundColor;
	                document.getElementById(document.getElementById("hrefDivId").value).setAttribute("color",color);
	                document.getElementById(document.getElementById("hrefDivId").value).style.fontFamily = fontFamily;
	                document.getElementById(document.getElementById("hrefDivId").value).style.fontSize = fontSize;
	            }
		        $(this).dialog('close');
	        },
	        Cancel: function() {
		        $(this).dialog('close');
	        }
	        
        }
    });
   $("#textSet").dialog('open');  
}

function ImageAdd(obj)
{
	  document.getElementById("bgimgdiv").appendChild(obj);
	  $(obj).addClass("flair-add");
	  $(obj).draggable({ containment: 'parent' });
      obj.style.position = "fixed";
      obj.style.left = "25px";
      obj.style.top = "25px";
      obj.style.zIndex = "99999";
	  $(obj).unbind('click');
}

function ImageRemove(obj)
{
	  $("#" + $(obj).attr("tab")).append(obj);
      $(obj).click(function(){
        ImageAdd(this);
      });
	  $(obj).removeClass("flair-add");
	  $(obj).unbind('draggable');
      obj.style.position = "";
      obj.style.left = "";
      obj.style.top = "";
      obj.style.zIndex = "99999";
}


function ProtocolSet(protocol)
{
    document.getElementById('hrefLink').value = document.getElementById('hrefLink').value.replace("http://","");
    document.getElementById('hrefLink').value = document.getElementById('hrefLink').value.replace("mailto:","");
    document.getElementById('hrefLink').value = protocol + document.getElementById('hrefLink').value;
    
}

function ElemRemove(id)
{
	var d = document.getElementById("bgimgdiv");
	var olddiv = document.getElementById(id);
	d.removeChild(olddiv);
}

function HrefSet(id)
{
	var div = document.getElementById(id);
	document.getElementById("hrefDivId").value = id;
	var href;
	if(div.getAttribute("href"))
	{
	    href = div.getAttribute("href");
	}
	else
	{
	    href = "http://";
	}
	document.getElementById("hrefLink").value = href;
	var bgColor;
	if(div.getAttribute("bgColor"))
	{
	    bgColor = div.getAttribute("bgColor");
	}
	else
	{
	    bgColor = "#0000FF";
	}
    document.getElementById("bgColor").value = bgColor;	
    document.getElementById("bgColorShow").style.backgroundColor = bgColor;
	if(href)
	{
	        $("#hrefGet").dialog({
	            autoOpen: false,
		        bgiframe: true,
		        height: 475,
		        width: 450,
		        title: 'Internet Address',
		        modal: false,
		        buttons: {
			        Ok: function() {
			            href = document.getElementById("hrefLink").value;
			            var div = document.getElementById(document.getElementById("hrefDivId").value);
			            if(href)
			            {
			                div.setAttribute("href",href);
			            }
			            bgColor = document.getElementById("bgColor").value;
			            if(bgColor)
			            {
			                div.setAttribute("bgColor",bgColor);
			            }
				        $(this).dialog('close');
			        },
			        Cancel: function() {
				        $(this).dialog('close');
			        }
			        
		        }
	        });
	       $("#hrefGet").dialog('open');  
	}
}

function DataPost()
{
    try
    {
        var username = $('#username').val();
        if(document.getElementById('altname'))
        {
            if($('#altname').val().length > 0)
            {
                username = $('#altname').val();
            }
        }
        
        $("#Saving").dialog({
            autoOpen: false,
            bgiframe: true,
            height: 250,
            title: 'Save',
            modal: false,
            buttons: {
                Close: function() {
                    $(this).html("<h2>Saving...</h2>");
	                $(this).dialog('close');
                }
    	        
            }
        });
    
        $("#Saving").dialog('open');  
        $.ajax({
            url:"save.aspx",
            data: "userid=" + escape($('#userid').val()) + "&username=" + escape(username) + "&oauth_token=" + escape($('#token').val()) + "&oauth_secret=" + escape($('#token_secret').val()) + "&data=" + escape($('#map').val()),
            success: function(data, textstatus){
              $("#Saving").dialog('close');  

            },          
            error: function (XMLHttpRequest, textStatus, errorThrown) {
       	        $("#Saving").html("<p style='color:red'>The information could not be saved.</p>");
            }
          });	
    }
    catch(e)
    {
        alert(e);
    }

}

function MapCreate()
{
    areas = "";
    $('*[id^=divMap]').each(function() {
        var href = document.getElementById(this.id).getAttribute("href");
        var bgColor = document.getElementById(this.id).getAttribute("bgColor");
        if(!bgColor)
        {
            bgColor = "#0000FF";
        }
        if(href.length > 1000)
        {
            href = href.substr(0,1000);
        }
        if(bgColor.length > 7 && bgColor != "transparent")
        {
            bgColor = "#0000FF";
        } 
        if(bgColor.length < 7)
        {
            bgColor = bgColor + "0000000";
            bgColor = bgColor.substr(0,7);
        }       
        if(bgColor.indexOf('#') < 0 && bgColor != "transparent")
        {
            if(bgColor.length == 7)
            {
                bgColor = '#' + bgColor.substring(1,6);              
            }
        }       
        if(href)
        {
            href = href.replace(',','\\,').replace('{','\\{').replace('}','\\}').replace('[','\\[').replace(']','\\]').replace('"','\\"').replace("'","\\'");
        }
        if(bgColor)
        {
            bgColor = bgColor.replace(',','\\,').replace('{','\\{').replace('}','\\}').replace('[','\\[').replace(']','\\]').replace('"','\\"').replace("'","\\'");
        }
        
        var top = this.offsetTop;
        var left = this.offsetLeft;
        var right = left + $("#" + this.id).width();
        var bottom = top + $("#" + this.id).height();
        if(areas.length > 0)
        {
            areas += ",";
        }
        areas += '{"coords":"' + left + ',' + top + ',' + right + ',' + bottom + '","href":"' + href + '","color":"' + bgColor + '"}';

	}); 
	
	document.getElementById("map").value = '{"areas":{"area":[' + areas + ']}}';
	DataPost();
}

function NotesCreate()
{
    var areas = "";
    $('*[id^=divNote]').each(function() {
        var note = $("#" + this.id + " > .txtnote").html();
        if(note)
        {
            note = note.replace(',','\\,').replace('{','\\{').replace('}','\\}').replace('[','\\[').replace(']','\\]').replace('"','\\"').replace("'","\\'");
        }
        
        var color = $("#" + this.id + " > .txtnote").attr("color");
        var fontFamily = $("#" + this.id + " > .txtnote").css("font-family");
        var fontSize = $("#" + this.id + " > .txtnote").css("font-size");
        if(!color)
        {
            color = "#000000";
        }
        if(color.length > 7 && color != "transparent")
        {
            color = "#000000";
        } 
        if(color.length < 7)
        {
            color = color + "0000000";
            color = color.substr(0,7);
        }       
        if(color.indexOf('#') < 0 && color != "transparent")
        {
            if(color.length == 7)
            {
                color = '#' + color.substring(1,6);              
            }
        }
        $("#" + this.id + " > .txtnote").css("color",color);       
        if(color)
        {
            color = color.replace(',','\\,').replace('{','\\{').replace('}','\\}').replace('[','\\[').replace(']','\\]').replace('"','\\"').replace("'","\\'");
        }        
        
        var top = this.offsetTop;
        var left = this.offsetLeft;
        var right = left + $("#" + this.id).width();
        var bottom = top + $("#" + this.id).height();
        if(areas.length > 0)
        {
            areas += ",";
        }
        areas += '{"coords":"' + left + ',' + top + ',' + right + ',' + bottom + '","note":"' + note + '","color":"' + color + '","fontFamily":"' + fontFamily + '","fontSize":"' + fontSize + '"}';

	}); 
	if(areas.length > 0)
	{
	    document.getElementById("notes").value = '{"areas":{"area":[' + areas + ']}}';
	}
	else
	{
	    document.getElementById("notes").value = '';
	}
}



function BackgroundNew()
{
    try
    {
        var flair_src = "";
        var flair_coords = "";
        $('.flair-add').each(function() {
            var top = this.offsetTop;
            var left = this.offsetLeft;
            var src = this.src;
            if(flair_src.length > 0)
            {
                flair_src    += ",";
                flair_coords += "@";
            }
            flair_src += src;
            flair_coords += left + "," + top;
         });
        
        var notes = "";
        var note_coords = ""; 
        $('*[id^=divNote]').each(function() {
            var note = $("#" + this.id + " > .txtnote").html();
            var top = this.offsetTop;
            var left = this.offsetLeft;
            var right = left + $("#" + this.id).width();
            var bottom = top + $("#" + this.id).height();
            var color = $("#" + this.id + " > .txtnote").attr("color");
            var fontFamily = $("#" + this.id + " > .txtnote").css("font-family");
            var fontSize = $("#" + this.id + " > .txtnote").css("font-size");
            note = "[" + fontFamily + "," + fontSize + "," +  color + "]" + note;
            if(notes.length > 0)
            {
                notes += "~";
                note_coords += "@";
            }
            notes += note;
            note_coords += left + "," + top + "," + right + "," + bottom;

	    }); 
         
    
        var username = $('#username').val();
        if(document.getElementById('altname'))
        {
            if($('#altname').val().length > 0)
            {
                username = $('#altname').val();
            }
        }
        
        $("#Saving").dialog({
            autoOpen: false,
            bgiframe: true,
            height: 250,
            title: 'Save',
            modal: false,
            buttons: {
                Close: function() {
                    $(this).html("<h2>Saving...</h2>");
	                $(this).dialog('close');
                }
    	        
            }
        });

        NotesCreate();
        if(flair_src.length > 0 || $("#notes").val().length > 0)
        {
            $('#savebg').dialog('open');        
            $('#ifmSavebg').attr("src","savebg.aspx?userid=" + escape($('#userid').val()) + "&username=" + escape(username) + "&oauth_token=" + escape($('#token').val()) + "&oauth_secret=" + escape($('#token_secret').val()) + "&data=" + escape(flair_src + "|" + flair_coords) + "&bg=" + escape(document.getElementById("bgimage").src) + "&notes=" + escape($('#notes').val()) + "&notesdata=" + escape(notes + "|" + note_coords));        
        }
        else
        {
            alert("Please add an image or textbox to your background.");
        }

    }
    catch(e)
    {
        alert(e);
    }

}


function DeleteAll()
{
    if(confirm("This action will remove all links and delete your ClickableNow account.\n\nAre you sure you want to continue?"))
    {
        areas = "";
        $('*[id^=divMap]').each(function() {
            ElemRemove(this.id);
	    }); 
    	document.getElementById("map").value = '';
	    DataPost();
	}
}


function MapRead()
{
    var r = eval("("+document.getElementById("map").value+")");
    
    if( r.areas.area && r.areas.area.length > 0 )
    {
        for(var ndx = 0;ndx < r.areas.area.length; ndx++)
        {
            var div = ElemAdd();
            var coords = r.areas.area[ndx].coords.split(",");
            div.style.left = coords[0] + "px";
            div.style.top = coords[1] + "px";
            div.style.width = parseInt(coords[2]) - parseInt(coords[0]) + "px";
            div.style.height = parseInt(coords[3]) - parseInt(coords[1]) +  "px";
            div.setAttribute("href",r.areas.area[ndx].href);
            var color = "#0000FF";
            if(r.areas.area[ndx].color)
            {
                color = r.areas.area[ndx].color;
            }
            div.setAttribute("bgColor",color);
        }
    }
}

function NotesRead()
{
    var notes = "";
    var r = eval("("+document.getElementById("notes").value+")");
    
    if( r.areas.area && r.areas.area.length > 0 )
    {
        for(var ndx = 0;ndx < r.areas.area.length; ndx++)
        {
            var div = TextElemAdd();
            var coords = r.areas.area[ndx].coords.split(",");
            div.style.left = coords[0] + "px";
            div.style.top = coords[1] + "px";
            div.style.width = parseInt(coords[2]) - parseInt(coords[0]) + "px";
            div.style.height = parseInt(coords[3]) - parseInt(coords[1]) +  "px";
            $("#" + div.id + " > .txtnote").html(r.areas.area[ndx].note);
            $("#" + div.id + " > .txtnote").css("color",r.areas.area[ndx].color);
            $("#" + div.id + " > .txtnote").attr("color",r.areas.area[ndx].color);
            $("#" + div.id + " > .txtnote").css("font-family",r.areas.area[ndx].fontFamily);
            $("#" + div.id + " > .txtnote").css("font-size",r.areas.area[ndx].fontSize);            
        }
    }
}


function BackgroundGet()
{
    try
    {
        var username = $('#username').val();
        if(document.getElementById('altname'))
        {
            if($('#altname').val().length > 0)
            {
                username = $('#altname').val();
            }
        }
        
        $("#Saving").html('<h2>Loading...</h2>');
        $("#Saving").dialog({
            autoOpen: false,
            bgiframe: true,
            height: 250,
            title: 'Load',
            modal: false,
            buttons: {
                Close: function() {
                    $(this).html("<h2>Saving...</h2>");
	                $(this).dialog('close');
                }
    	        
            }
        });
    
        $("#Saving").dialog('open');  
        $.ajax({
            url:"bgload.aspx",
            data: "userid=" + escape($('#userid').val()) + "&username=" + escape(username) + "&oauth_token=" + escape($('#token').val()) + "&oauth_secret=" + escape($('#token_secret').val()),
            success: function(data, textstatus){
              document.getElementById("bgurl").value = data;   
              document.getElementById("bgimage").setAttribute("src",document.getElementById("bgurl").value);
              $("#Saving").dialog('close');  

            },          
            error: function (XMLHttpRequest, textStatus, errorThrown) {
       	        $("#Saving").html("<p style='color:red'>The background could not be loaded.</p>");
            }
          });	
    }
    catch(e)
    {
        alert(e);
    }
}

function BackupGet()
{
    try
    {
        var username = $('#username').val();
        if(document.getElementById('altname'))
        {
            if($('#altname').val().length > 0)
            {
                username = $('#altname').val();
            }
        }
        
        $("#Saving").html('<h2>Loading...</h2>');
        $("#Saving").dialog({
            autoOpen: false,
            bgiframe: true,
            height: 250,
            title: 'Load',
            modal: false,
            buttons: {
                Close: function() {
                    $(this).html("<h2>Saving...</h2>");
	                $(this).dialog('close');
                }
    	        
            }
        });
    
        $("#Saving").dialog('open');  
        $.ajax({
            url:"bgload.aspx",
            data: "userid=" + escape($('#userid').val()) + "&username=" + escape(username) + "&oauth_token=" + escape($('#token').val()) + "&oauth_secret=" + escape($('#token_secret').val()) + "&backup=true",
            success: function(data, textstatus){
              document.getElementById("bgurl").value = data;   
              document.getElementById("bgimage").setAttribute("src",document.getElementById("bgurl").value);
              $("#Saving").dialog('close');  

            },          
            error: function (XMLHttpRequest, textStatus, errorThrown) {
       	        $("#Saving").html("<p style='color:red'>The background could not be loaded.</p>");
            }
          });	
    }
    catch(e)
    {
        alert(e);
    }

}

function BackupDelete()
{
    try
    {
        var username = $('#username').val();
        if(document.getElementById('altname'))
        {
            if($('#altname').val().length > 0)
            {
                username = $('#altname').val();
            }
        }
        
        $("#Saving").html('<h2>Deleting...</h2>');
        $("#Saving").dialog({
            autoOpen: false,
            bgiframe: true,
            height: 250,
            title: 'Delete',
            modal: false,
            buttons: {
                Close: function() {
                    $(this).html("<h2>Saving...</h2>");
	                $(this).dialog('close');
                }
    	        
            }
        });
    
        $("#Saving").dialog('open');  
        $.ajax({
            url:"bgload.aspx",
            data: "userid=" + escape($('#userid').val()) + "&username=" + escape(username) + "&oauth_token=" + escape($('#token').val()) + "&oauth_secret=" + escape($('#token_secret').val()) + "&backupdelete=true",
            success: function(data, textstatus){
              $("#Saving").dialog('close');  

            },          
            error: function (XMLHttpRequest, textStatus, errorThrown) {
       	        $("#Saving").html("<p style='color:red'>The background could not be loaded.</p>");
            }
          });	
    }
    catch(e)
    {
        alert(e);
    }

}


function SetupPP()
{
    var ret = false;
    
    if($('#userid').val().length > 0)
    {
        $('#custom').val($('#userid').val() + "|" + $('#token').val() + "|" + $('#token_secret').val());
        ret = true;
    }
    else
    {
        alert("Please signin to Twitter first.");
    }
    return ret;
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
