/**
 * Chartly - General JS
 */
 
 
 /*****************************************************************************************
 * General 
 */

 /**
  * ClickToClear (called onfocus && onblur)
  */
 function clickToClear(element) {
 	if(element.value == "") {
 		element.value = element.getAttribute("defaultvalue");
 	}
 	else if(element.value == element.getAttribute("defaultvalue")) {
 		element.value = "";
 	}
 }
 
 /*****************************************************************************************
  * Settings
  */
  
 /**
  * Validate 
  */  
 function _validateSettings() {
 	if(dojo.byId("settings_action").value == "enable") {
	 	if(dojo.byId("twitter_password").value == "") {
	 		alert("Please enter your Twitter password to continue");
	 		return false;
	 	}
 	}
 	if(dojo.byId("settings_action").value == "disable") {
 		
 		if(!confirm("Are you sure you wish to disable Mobile Upload?")) {
 			return false;
 		}
 	}

 	return true;
 }

 /**
  * Generate a new movile email address
  */  
 function _generateNewMobileEmailAddress() {
 	if(confirm("Are you sure you wish to generate a new Mobile Upload email address?\nNOTE - Your current email address will be deleted")) {
	 	var _form = dojo.byId("settings_form");
	 	dojo.byId("settings_action").value = "regenerate";
	 	_form.submit();
 	}
 }
 
 function _updateMobilePw() {
 	if(dojo.byId("twitter_password").value == "" 
 	|| dojo.byId("twitter_password").value == dojo.byId("twitter_password").getAttribute("defaultValue")) {
 		alert("Please enter your Twitter password to continue");
 		return;
 	}
 	var _form = dojo.byId("settings_form");
 	dojo.byId("settings_action").value = "update";
 	_form.submit();
 }

 
 /*****************************************************************************************
  * Classic Login
  */
  
 /**
  * Validate login
  */  
 function _validateLogin() {
 	if(dojo.byId("username").value == "" 
 	|| dojo.byId("username").value == dojo.byId("username").getAttribute("defaultValue")) {
 		alert("Please enter a username.");
 		return false;
 	}
 	else if(dojo.byId("password").value == "" 
 	|| dojo.byId("password").value == dojo.byId("password").getAttribute("defaultValue")) {
 		alert("Please enter a password.");
 		return false;
 	}
 	
 	_disableLoginControls(true);
 	return true;
 }
  
 /**
  * Disable or enable login controls
  */ 
 function _disableLoginControls(disable) {
 	if(disable) {
 		dojo.byId("cancel_login").setAttribute("disabled", true);
 		dojo.byId("submit_login").setAttribute("disabled", true);
 	}
 	else {
 		dojo.byId("cancel_login").removeAttribute("disabled");
 		dojo.byId("submit_login").removeAttribute("disabled");
 	}
 }
 
 /**
  * Display login (and hide sub heading)
  */
 function _displayClassicLogin() {
 	dojo.byId("classic_login").style.display = "block";
 	dojo.byId("login").style.display = "none";
 	dojo.byId("sub_heading").style.display = "none";
 }
 
 /**
  * Hide login
  */
 function _hideClassicLogin() {
 	dojo.byId("classic_login").style.display = "none";
 	dojo.byId("login").style.display = "inline";
 	dojo.byId("sub_heading").style.display = "block";
 }
 
 
/*****************************************************************************************
 * View Chart 
 */
 
 /**
  * Make sure the width of the chart is under the max -If it is not, resize it.
  */
 function _checkMaxChartSize(max_width) {
 	var img = dojo.byId("chart_image");
 	if(img.width >= max_width) {
 		var view_full_link = dojo.byId("view_chart_fullsize");
 		view_full_link.style.visibility = "visible";  		
 	}
 }
 
 /**
  * View lightbox img
  */
 function _viewLightBox(img_src, title) {
 	
	//create local function...
	var _show = function() {
		var lb = new dojox.image.Lightbox({href:img_src, title:(title? title : null)	});
		lb.startup();
		lb.show();
		};
	
	if(!dojox || !dojox.image) {
		//load lightbox files, and display...
		dojo.require("dojox.image.Lightbox");
		dojo.addOnLoad(_show); 
	}
	else {
		//lightbox files loaded, just display...
		_show();
	}
 }

 /**
  * Delete supplied chart
  */
 function _deleteChart(id) {
 	if(confirm("Are you sure you wish to permanently delete this chart?")) {
 		window.location.href = "chart.delete?id=" + id;
 	}
 }


/*****************************************************************************************
 * Search 
 */

 
 /**
  * Search!
  * (abs path provided)
  */
 function _search(path) {
 	var search_val = dojo.byId('search_text').value;
 	
 	if(search_val != dojo.byId('search_text').getAttribute("defaultvalue")) {
	 	var url = path + "search?q=" + search_val;
	 	url = url.replace(/\s/g,"+");
	 	window.location.href= url;
 	}
 	else {
 		alert("Ooops! Please enter a search term");
 	}
 }
 
 /**
  * Monitor search for for 'enter' key
  */
 function _onsearch_keypress(e, path) {
 	if(e.keyCode == 13) {
 		_search(path);
 	}
 }

/*****************************************************************************************
 * Upload
 */

  /**
  * Validate Upload data
  */ 
 function _validateUploadForm() {
 	//get properties...
 	var filename = dojo.byId("asset").value;
 	var symbol_txt = dojo.byId("stock_symbol").value;
	var tags_txt = dojo.byId("tags").value;
	var tweet_txt = dojo.byId("description").value;
	

	//make chart iamge has been set...
	if(filename == "" || filename == null) {
		alert("Please select a Chart image to upload...");
		return false;
	}
	
	//make sure chart extension valid
	var valid_extensions = {"GIF": true, "PNG": true, "JPG": true, "JPEG": true};
	var extension = (filename.lastIndexOf(".") > -1 ? (filename.substring(filename.lastIndexOf(".")+1).toUpperCase()) : null);
	
	if(!valid_extensions[extension]) {
		alert("File type not supported, must be either GIF, JPG, or PNG");
		return false;
	}
	
	//make sure we have a symbol..
	if(symbol_txt == "" || symbol_txt == "$") {
		alert("Please enter a Stock Symbol for this Chart (e.g. $GOOG)");
		return false;	
	} 
	
	//if we have tags, make sure they are valid
	if(tags_txt != "") {
		//split tags into array...
		var tags_arr = tags_txt.split(",");
		//loop
		for(i = 0; i < tags_arr.length; i++) {
			var _tag = dojo.trim(tags_arr[i]);
			//validate single tag..
			if(!_validateTag(_tag)) {
				return false;
			}
		}
		//tags are valid..
	}
	
	if(tweet_txt.length > 100) {
		alert("Too many characters, Maximum Chart description length is 100.");
		return false;
	}
	
	return true;
 } 

/*****************************************************************************************
 * Manage tags 
 */
 
 /**
  * Add the specified tag
  */
 function _addTag() {
 	var tag = window.prompt("Enter tag:", "");
 	//make sure we got a tag..
 	if(tag != "" && tag != null && _validateTag(tag)) {
 		dojo.byId("tag_action").value = "ADD";
 		dojo.byId("tag_text").value = tag;
 		dojo.byId("tags_manage_form").submit();
 	}
 }
 
 /**
  * Edit the supplied tag
  */
 function _editTag(tag, e) {
 	var edit_tag = window.prompt("Edit tag:", tag);
 	//make sure we got a tag..
 	if(edit_tag != "" && edit_tag != null && edit_tag != tag && _validateTag(edit_tag)) {
 		dojo.byId("tag_action").value = "EDIT";
 		dojo.byId("tag_text").value = tag;
 		dojo.byId("tag_edit").value = edit_tag;
 		dojo.byId("tags_manage_form").submit();
 	}
 } 
 
 /**
  * Removed the specified tag
  */
 function _removeTag(tag) {
 	if(window.confirm("Are you sure you wish to remove this tag?")) {
 		dojo.byId("tag_action").value = "DELETE";
 		dojo.byId("tag_text").value = tag;
 		dojo.byId("tags_manage_form").submit();
 	}
 } 
 
 /**
  * Validate tag
  */ 
function _validateTag(tag) {
	var reg_ex = /^([a-zA-Z0-9_-]+)$/;
	if(!reg_ex.test(tag))
	{
		alert("Whoops, Invalid Character!\nTags can only contain letters, numbers, dashes and underscores.");
		return false;
	} 

	if(tag.length > 17)
	{
		alert("Whoops, the length of this Tag is too long! Please keep it under 18 characters - Thanks!");
		return false;
	} 	
	
	return true;
} 


/*****************************************************************************************
 * Manage comments
 */

  /**
  * Validate Comment
  */ 
 function _validateComment() {
 	var comment_txt = dojo.byId("comment_text").value;

	if(comment_txt == "" || comment_txt == null) {
		alert("Please enter the text for this comment");
		return false;
	} else if(comment_txt.length > 140) {
		alert("Too many characters, Maximum comment length is 140!");
		return false;
	}
	return true;
 } 
 
 /*
 *this function limits the number of characters entered into the value field of inputElement
 * based on maxlength and updates the remainig count in the innerHTML of outputElement
 */
 function limitInputSize(maxlength, inputElement, outputElement)
 {
 	if(inputElement.value.length > maxlength) 
 	{
 		inputElement.value = inputElement.value.substring(0, maxlength);
 	} 
 	outputElement.innerHTML = (maxlength - inputElement.value.length)
 }
 
 
 
  /*
 *this is for the side menu hiding and showing
 */
 
function hideMenu(nodeid)
{
	element = dojo.byId(nodeid);
	if(element != null)
	{
		if(element.style.display != "none")
		{
			t = new dojo.fx.Toggler({
			node: nodeid,
			showDuration: 1000,
			showFunc: dojo.fx.wipeIn,
			hideDuration : 500,
			hideFunc: dojo.fx.wipeOut
	
			});
			t.hide(500);
		}
	}
}

function showHide(nodeid)
{

	element = dojo.byId(nodeid);
	if(element.style.display == "none")
	{
	t = new dojo.fx.Toggler({
		node: nodeid,
		showDuration: 500,
		showFunc: dojo.fx.wipeIn,
		hideFunc: dojo.fx.wipeOut
		});
		
		t.show(100); // delay showing for 100ms
		}

	if("related_list" != nodeid)
	{
		hideMenu("related_list");
	}
	if("popular_users" != nodeid)
	{
		hideMenu("popular_users");
	}
	if("popular_list" != nodeid)
	{	
		hideMenu("popular_list");
	}
	
	

}

/******
*Refresh dynamic content
*****/

function getCharts(parentNode) 
	{
	
	//parentNode.innerHTML = '<span class="loading">Getting Recent Charts...</span>';
	
      dojo.xhrPost( {      
        url: "include/content/latest_charts.php", 
        handleAs: "text",
			content: {},
        timeout: 5000, // Time in milliseconds

        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) {
    		
       	if(response.error)
       	{
       		alert(response.error);
       	}
       	else
       	{       		
				
				parentNode.innerHTML = response;
       		
       		setTimeout("getCharts(dojo.byId('" + parentNode.id + "'))", '20000')
       	}	
       
          return response;
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) {
          //alert("HTTP status code: ", ioArgs.xhr.status);  
          //alert(response);       
          return response;
          }
        });
    
 	}

	function getComments(datetime, parentNode) 
	{
		
	
      dojo.xhrPost( {      
        url: "include/content/latest_comments.php", 
        handleAs: "text",
			content: {lastdatetime:datetime},
        timeout: 5000, // Time in milliseconds

        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) {
    		
       	if(response.error)
       	{
       		alert(response.error);
       	}
       	else
       	{       		
				var tempdiv = dojo.doc.createElement("div");
				tempdiv.innerHTML  = response;				
				
				newkids = dojo.query(".comment", tempdiv);
				
				kids = dojo.query(".comment", parentNode);							
				
				nextdateList = dojo.query(".lastdate", tempdiv);							
				
				nextdate = datetime;
				if(nextdateList.length > 0)
				{
					nextdate = nextdateList[0].innerHTML;					
				}
				
				if(kids.length + newkids.length > 15)
				{
					removecount = (kids.length + newkids.length) - 15;
					//alert(removecount);					
					
					for(i = 0; i < removecount; i++)
					{						
						
						/*t = new dojo.fx.Toggler({
							node: kids[(kids.length - 1) - i].id,
							showDuration: 500,
							showFunc: dojo.fx.wipeIn,
							hideFunc: dojo.fx.wipeOut
							});
					t.hide(500);*/
						try
						{
							parentNode.removeChild(kids[(kids.length - 1) - i]);
						}
						catch(ex)
						{
							//ignore
						}
					}
				}
							
				for(i = newkids.length - 1;i > -1; i--)
				{
					parentNode.insertBefore(newkids[i], parentNode.firstChild);
					newkids[i].style.display='none';
					
							t = new dojo.fx.Toggler({
							node: newkids[i].id,
							showDuration: 500,
							showFunc: dojo.fx.wipeIn,
							hideFunc: dojo.fx.wipeOut
							});
					t.show(500);
				}
			
       		
       		setTimeout("getComments('" + nextdate + "', dojo.byId('" + parentNode.id + "'))", '20000')
       	}	
       
          return response;
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) {
          //alert("HTTP status code: ", ioArgs.xhr.status);  
          //alert(response);       
          return response;
          }
        });
    
 	}


