var removeElementChildren = function(parentID){
	parent = document.getElementById(parentID);
	
	if (parent.hasChildNodes()) {
			while (parent.childNodes.length >= 1 ) {
				parent.removeChild(parent.firstChild );       
			} 
		}
}

var checkParentSize = function() {      	 	
	hideFormPost();
	var parentTextArea1 = document.getElementById('photocommentbox1');
	var commentArea1 = document.createElement('textarea');
	commentArea1.setAttribute("name","commentbox");
	commentArea1.setAttribute("id","commentbox");
	commentArea1.setAttribute("cols","");
	commentArea1.setAttribute("rows","");
	parentTextArea1.appendChild(commentArea1);
            	
	var parentTextArea2 = document.getElementById('photocommentbox2');	
	var commentArea2 = document.createElement('textarea');
	commentArea1.setAttribute("name","commentbox2");
	commentArea1.setAttribute("id","commentbox2");
	commentArea1.setAttribute("cols","");
	commentArea1.setAttribute("rows","");
	parentTextArea2.appendChild(commentArea2);
            	
	showFormPost();
}

function clearTagField() {
	if (document.getElementById("tag_field").value == 'Add tag seperate by commas') {
		document.getElementById("tag_field").value = ''	
	}
}

function clearArtisCommentBox() {
	if (document.getElementById("artisCommentBox").value == 'Type text and click outside of the area to save') {
		document.getElementById("artisCommentBox").value = ''	
	}
}

function changeImageTitle() {
 	var div = document.getElementById('image_title_block');
	var imageName = document.getElementById('image_title').innerHTML;
	div.innerHTML = '<input onblur="return saveImageTitle()" type="text" class="textBox" id="image_title" value="' + imageName + '" />';
	document.getElementById('image_title').focus();
}

function changeUserTitle() {
 	var div = document.getElementById('user_title_block');
	var userTitle = document.getElementById('user_title').innerHTML;
	div.innerHTML = '<input onblur="return saveUserTitle()" type="text" class="textBox userTitle" id="user_title" value="' + userTitle + '" />';
	document.getElementById('user_title').focus();
}

function changeArtistComment() {
	var div = document.getElementById('artist_comment_block');
	var artistComment = '';
	var artistCommentHTML = document.getElementById('artistCommentContent').value;
	
	artistCommentHTML = artistCommentHTML.replace(/<br.*?\/?>/ig, "\n");
	if(artistCommentHTML !='Type text and click outside of the area to save') {
		artistComment = artistCommentHTML;
	}
	
	div.innerHTML = '<textarea onblur="return saveArtistComment()" style="width:550px;height:80px;margin-bottom:15px;	padding-top:4px;padding-left:3px;background:#D1D1D1 none repeat scroll 0 0;border:1px solid #6666CC;color:#040404;font-size:16px;font-weight:bold;" id="artist_comment_textarea" >'+ artistComment + '</textarea>';
	document.getElementById('artist_comment_textarea').focus();
}

function saveUserTitle2() {
	// there is ajax call
 	var div = document.getElementById('user_title_block');
	div.innerHTML = "<span id='user_title' onclick='changeUserTitle()'>" + document.getElementById('user_title').value + "</span>";
	var newTitle = document.getElementById('user_title').value;
	return false;
}

var refreshTags = function(request, json) {
	var tags = json.tags;
	var success = json.success;
	
	if(success != true) {
		showAlert("Images limit exceeded for this community, Try again later.");
	}

	var parentCommunity = jQuery('#community_div');
	var communityImage = json.community_images;
	var communityCount = json.community_count;		
	
	if(communityImage) {
		parentCommunity.html('');
		for (i = 0; i < communityCount;i++) {
			var spanEl = document.createElement('span');
			spanEl.className = "classicIcons"
			spanEl.id = 'communityTag' + communityImage[i].id;
			var aEl = document.createElement('a');
			aEl.setAttribute('href', '/communities/'+communityImage[i].community_name);
			var aText = document.createTextNode(communityImage[i].community_name);
			
			var label = document.createElement('label');
		    label.setAttribute("onclick", "removeFromCommunity(" + communityImage[i].id + ")");
		    label.className = 'clickable'		    
		    var labelText = document.createTextNode("x");
		    label.appendChild(labelText);
			
			aEl.appendChild(aText);
			spanEl.appendChild(aEl);
			spanEl.appendChild(label);			
			parentCommunity.append(spanEl);
		}
	}
	var parent = jQuery('#taglist');
	removeElementChildren('taglist');
	if(tags!=null) {
		var countTags = json.tags.length;
		for (i = 0; i < countTags;i++) {               
			var tag = document.createElement('span');
			tag.id = 'tag'+i;
			var text = document.createTextNode(tags[i]);
		                
		    var label = document.createElement('label');
		    label.setAttribute("onclick","deleteTag('"+tags[i]+"','tag"+i+"')");
		    var labelText = document.createTextNode("  x");
		    label.appendChild(labelText);
		                
		    tag.appendChild(text);
		    tag.appendChild(label);
		    parent.append(tag);
		}
	}
}

var refreshOnComplete = function(request, json) {
	
	var img  = json.image;
   	var tags = json.tags;
	var commentsCount = json.commentsCount;
	
	document.getElementById('favedTimes').innerHTML = json.favTimes;
	if(json.isFav) {
		document.getElementById('favorite').className = 'FavImglink'; 
	}else {
		document.getElementById('favorite').className = 'UnFavImglink';
	}

	//START update comments count
	
	removeElementChildren('commentCounter');
	var counter = document.createTextNode(commentsCount+' Comments');
	document.getElementById('commentCounter').appendChild(counter);
	onLoadAllComments(false,json);
	//END 

	document.getElementById("image-frame").style.width = parseInt(json.sizeX) + 49 + "px";  
    document.getElementById('demo-run').src= 'http://megashot.net/sbushinskii/mvc/photo_photopage/'+img.filename;
    document.getElementById('image_title').innerHTML = img.title+'&nbsp;&nbsp;';
    document.getElementById("hidden_image_id").value = img.fileId;
    
    var newUrl = 'http://'+json.author_screen_name+'.megashot.net/photos/'+img.fileId+'#';
    var parent = document.getElementById('taglist');
	removeElementChildren('taglist');
	
	removeElementChildren('community_div');
	
	var parentCommunity = jQuery('#community_div');
	
	var communityImage = json.community_images;
	var communityCount = json.community_count;
	if(communityCount>0){
		for (i = 0; i < communityCount;i++) {
			var spanEl = document.createElement('span');
				var aEl = document.createElement('a');
					aEl.setAttribute('href','http://megashot.net/communities/'+communityImage[i].community_name);
						var aText = document.createTextNode(communityImage[i].community_name);
					aEl.appendChild(aText);
				spanEl.appendChild(aEl);
			parentCommunity.append(spanEl);
		}
	}
	
	if(tags!=null) {
		var countTags = json.tags.length;
		if (parent.hasChildNodes()) {
			while (parent.childNodes.length >= 1 ) {
				parent.removeChild(parent.firstChild );       
			} 
		}
					
       	for (i = 0; i < countTags;i++) {               
			var tag = document.createElement('span');
			tag.id = 'tag'+i;
			var text = document.createTextNode(tags[i]);
		                
		    var label = document.createElement('label');
		    label.setAttribute("onclick","deleteTag('"+tags[i]+"','tag"+i+"')");
		    var labelText = document.createTextNode("  x");
		    label.appendChild(labelText);
		                
		    tag.appendChild(text);
		    tag.appendChild(label);
		    parent.appendChild(tag);
		}
	}
	              
	var menuExploreItem = document.getElementById('exploreMenuItems');
	              
	if (menuExploreItem.hasChildNodes()) {
		while (menuExploreItem.childNodes.length >= 1 ) {
		   menuExploreItem.removeChild(menuExploreItem.firstChild );       
		} 
	}

	var categoryExploreCount = json.exploreCategoryItemsCount;
	var exploreCat = json.exploreCategoryItems;
				  
	for (var i=0;i<categoryExploreCount;i++) {
		var catTR = document.createElement('TR');
		var catTD = document.createElement('TD');
		var catA  = document.createElement('a');				  				
		var imageId = img.fileId;
		var catId   = i+1;
		var catName = exploreCat[i];

		catA.setAttribute('onclick','isImageInCategory("'+imageId+'","'+catId+'")');
		catA.innerHTML = catName;
					  			
  		catTD.appendChild(catA);			  		
	  	catTR.appendChild(catTD);
		menuExploreItem.appendChild(catTR);
	}
	
	//----------- START FUN - listCommunities ----------	
	listCommunities(1);
	listCommunities(2);
	//----------- END FUN - listCommunities ----------
	//----------- START FUN - clearCommentboxes ----------
	clearCommentboxes()
	//----------- START FUN - clearCommentboxes ----------
	window.scrollTo(0, 60);
	jQuery.unblockUI();	
}
            
function URLEncode (clearString) {
	var output = '';
	var x = 0;
	clearString = clearString.toString();
	var regex = /(^[a-zA-Z0-9_.]*)/;
	while (x < clearString.length) {
		var match = regex.exec(clearString.substr(x));

		if (match != null && match.length > 1 && match[1] != '') {
			output += match[1];
			x += match[1].length;
		} else {
			if (clearString[x] == ' ') {
	    	    output += '+';
			} else {
				var charCode = clearString.charCodeAt(x);
				var hexVal = charCode.toString(16);
				output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
			}
			x++;
		}
	}
	return output;
}

var goBack = function(){
	window.history.back();
}
