/**
 * Community pages Js Library
 * 
 * @author haqen
 * 
 */

var userInput = '';
var ajaxResponse = null;
var previewImages = null;
var totalImageCount = 0;
var loadedImageCount = 0;
var currentImage = 0;
var showContentBusy = false;
var scrolled = false;

function getSerializedTags() {
	if ($('#tagZone').children().length == 0) {
		return null;
	}
	var tags = new Array();
	for (var i = 1; i <= $('#tagZone').children().length; i++) {
		var value = $('#tagZone').find('div.tag:nth-child('+i+')').attr('data-value');
		if (value != null) { tags[i-1] = value; }		
	}
	return JSON.stringify(tags);
}

function tagFieldKeyPress(e) {
	if (e.which == 13) {
		if (e.ctrlKey) {
			tagFieldBlur();
			shareText();
		} else {
			var tag = $('#tagField').val();
			if (tag != localized['tagAddInfo'] && tag != '') {
				addTag(tag);
			}			
		}
	} else if (e.which == 8 && $('#tagField').val() == '') {
		removeLastTag();
	}
}

function previewKeywords(keywords) {	
	if (keywords == null || keywords == '') {
		return;
	}
	var tags = keywords.split(',');
	for (var i = 0; i < tags.length; i++) {
		addTag(tags[i]);
	}
}

function removeLastTag() {
	var count = $('#tagZone').children().length-1;
	$('#tagZone').find('div.tag:nth-child('+count+')').remove();
}

function removeTagButton() {
	$('#tagZone .tagDiv').remove();
}

function addTagButton() {
	var html = 
		'<div class="tagDiv float-left">' +
			'<div>' +
				'<span class="commonIcon ui-icon ui-icon-plus"></span>' +
				'<input id="tagField" class="tagFieldPassive" type="text" value="' + localized['tagAddInfo'] + '">' +
			'</div>' +
		'</div>';	
	$('#tagZone').append(html);
	$('#tagField').focus(tagFieldFocus);
	$('#tagField').blur(tagFieldBlur);
	$('#tagField').keypress(tagFieldKeyPress);
}

function addTag(str) 
{
	var tagValue = str.replace(/ /g, '.');
	for (var i = 1; i <= $('#tagZone').children().length; i++) {
		var value = $('#tagZone').find('div.tag:nth-child('+i+')').attr('data-value');
		if (value == tagValue) {
			return;
		}
	}
	var html = '<div data-value="' + tagValue + '" class="tag float-left">' +
					'<div class="tagButton ui-corner-all">' + str + 
						'<span class="commonIconR ui-icon ui-icon-close"></span>' + 
					'</div>' + 
				'</div>';
	removeTagButton();
	$('#tagZone').append(html);
	addTagButton();
	$('#tagField').focus();
	$('#tagZone .commonIconR').click(function(){removeTag($(this));});
	$('#tagField').val('');
}

function removeTag(item) {
	item.parent().parent().remove();
}

function tagFieldFocus() {
	$('#tagField').addClass('tagFieldActive');
	$('#tagField').removeClass('tagFieldPassive');
	if ($('#tagField').val() == localized['tagAddInfo']) {
		$('#tagField').val('');
	}
}

function tagFieldBlur() {
	$('#tagField').removeClass('tagFieldActive');
	$('#tagField').addClass('tagFieldPassive');
	if ($('#tagField').val() == '') {
		$('#tagField').val(localized['tagAddInfo']);
	} else if ($('#tagField').val() != '' && $('#tagField').val() != localized['tagAddInfo']) {
		addTag($('#tagField').val());
	}
}

function shareKeypress(e) {
	if (e.ctrlKey && e.keyCode == 13) {
		tagFieldBlur();
		shareText();
	}
}

function prepareShareBox() {
	$('#share').focus(shareFocus);
	$('#share').keypress(shareKeypress);
	$('#errorMsg').text(localized['errorGeneral']);
	$('#share').val(localized['shareText']);
	$('#share').autoResize({
	    // On resize:
	    onResize : function() {
	        $(this).css({opacity:0.8});
	    },
	    // After resize:
	    animateCallback : function() {
	        $(this).css({opacity:1});
	    },
	    // Quite slow animation:
	    animateDuration : 100,
	    // More extra space:
	    extraSpace : 20
	});	
}

function setViewed(id) {
	var arr = null;
	var json = getCacheData('twts');
	if (json == null || json == '') { arr = new Array(); } else { arr = eval(json); }
	if (arr[id] == null) {
		arr[id] = 1;
	} else {
		arr[id] = arr[id] + 1;
	}			
	json = JSON.stringify(arr);
	setCacheData('twts', json);
}

function twtShowAll(childItem) {
	var item = childItem.parent().parent().parent(); 
	var id = item.attr('id');
	if (item.attr('data-d') == '0') {
		item.attr('data-d', '1');
		$('#' + id + ' .contentDetails').first().show('slide');
		$('#' + id + ' .commentGroup').first().show('blind');
		$('#' + id + ' .ui-icon-circle-triangle-s').first().addClass('ui-icon-circle-triangle-n');
		$('#' + id + ' .ui-icon-circle-triangle-s').first().removeClass('ui-icon-circle-triangle-s');
	} else {
		item.attr('data-d', '0');
		$('#' + id + ' .contentDetails').first().hide('slide');
		$('#' + id + ' .commentGroup').first().hide('blind');
		$('#' + id + ' .ui-icon-circle-triangle-n').first().addClass('ui-icon-circle-triangle-s');
		$('#' + id + ' .ui-icon-circle-triangle-n').first().removeClass('ui-icon-circle-triangle-n');
	}
}

function twtZoomIn(childItem) 
{
	var item = childItem.parent().parent().parent(); 
	var id = item.attr('id');
	if (item.attr('data-d') == '0') {
		item.attr('data-d', '1');
		$('#' + id + ' .commentGroup').first().fadeIn();
	}
}

function isSupportsCanvas() {
	return !!document.createElement('canvas').getContext;
}

function setCacheData(key, value) {
	try {
		if (typeof(localStorage) !== 'undefined' && localStorage != null) {
			localStorage.setItem(key, value);
		} else if (typeof(localStorage) !== 'undefined' && localStorage != null) {
			globalStorage[key] = value;
		}
	} catch (err) {
		
	}
}

function getCacheData(key) {
	var value = null;
	try {
		if (typeof(localStorage) !== 'undefined' && localStorage != null) {
			value = localStorage.getItem(key);
		} else if (typeof(localStorage) !== 'undefined' && localStorage != null) {
			value = globalStorage[key];
		}
	} catch (err) {
		
	}
	return value;
}

function getData(id, name) {
	return $(id).attr('data-' + name);	
}

function setData(id, name, value) {
	$(id).attr('data-' + name, value);
}

function like(sender, hash, type) {	
	var method = null;
	var text = sender.text().trim();
	if (text == localized['like']) {
		method = type == 'comment' ? 'likeComment' : 'likeShare';
	} else if (text == localized['liked']) {
		method = type == 'comment' ? 'dislikeComment' : 'dislikeShare';
	}
	
	try {
		var query = 'ajax=true&method=' + method + '&data=' + hash;
		jQuery.ajax({
            type: 'POST',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            url: 'community/ajax/post',            
            data: query,
            success:function(response) {
            	sender.text(text == localized['like'] ? localized['liked'] : localized['like'] );
            },
            error:function (xhr, ajaxOptions, thrownError) {
            	showError(localized['shareError']);
            }    
        });
	} catch (e) {
		showError(localized['shareError']);
	}
}

function removeComment(item) {
	if (confirm(localized['removeContent'])) {
		// remove comment
		item.parent().fadeOut();
		try {
			var query = 'ajax=true&method=removeComment&data=' + item.attr('hash');
			jQuery.ajax({
	            type: 'POST',
	            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
	            url: 'community/ajax/post',            
	            data: query,
	            success:function(response) {
	            	
	            },
	            error:function (xhr, ajaxOptions, thrownError) {
	            	showError(localized['shareError']);
	            }    
	        });	
		} catch (e) {
			showError(localized['shareError']);
		}
	}
}

function removeShare(item) {
	if (confirm(localized['removeContent'])) {		
		// remove content
		try {
			var query = 'ajax=true&method=removeShare&data=' + item.attr('data-hash');
			jQuery.ajax({
	            type: 'POST',
	            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
	            url: 'community/ajax/post',            
	            data: query,
	            success:function(response) {
	            	$('#twt'+item.attr('data-hash')).fadeOut();
	            },
	            error:function (xhr, ajaxOptions, thrownError) {
	            	showError(localized['shareError']);
	            }    
	        });	
		} catch (e) {
			showError(localized['shareError']);
		}
	}
}

function getAjaxLoadingGif() {
	return '<img class="videoLoading" src="images/ajax1.gif" alt=""/>';
}

function showContents() {
	if ($('#contentPager').length == 0 || showContentBusy == true) {
		return;
	}
	showContentBusy = true;
	$('#contentPager').html(getAjaxLoadingGif());
	var start = Number(getData('#contentData', 'start'));
	try {
		var query = 'ajax=true&status=' + start;
		if (getData('#contentData', 'tag') != '') {
			query += '&method=showTagContents&data=' + getData('#contentData', 'tag');
		} else if (getData('#contentData', 'search-keyword') != '') {
			query += '&method=showSearchContents&data=' + getData('#contentData', 'search-keyword');
		} else if (getData('#contentData', 'content-user') != '') {
			query = 'ajax=true&method=showUserContents&status=' + start + "&data=" + getData('#contentData', 'content-user');
		} else if (getData('#contentData', 'content-user') == '') {
			var type = getData('#contentData', 'content-type'); 
			if (type == 'popular') {
				query += '&method=showPopularContents&data=' + getData('#contentData', 'content-user');
			} else if (type == 'latest') {
				query += '&method=showLatestContents&data=' + getData('#contentData', 'content-user');
			}
		} else {
			console.log('invalid request');
			return;
		}
		jQuery.ajax({
            type: 'GET',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            url: 'public/ajax/get',            
            data: query,
            success:function(response) {            	
            	$('#contentPager').remove();
            	$('#wallContent').html($('#wallContent').html() + response);            	
            	setData('#contentData', 'start', start+10);
            	showContentBusy = false;
            	prepare();
            },
            error:function (xhr, ajaxOptions, thrownError) {
            	showContentBusy = false;
            	showError(localized['shareError']);
            }    
        });	
	} catch (e) {		
		showContentBusy = false;
		showError(localized['shareError']);
	}
}

function showComments(hash, start) {
	$('.ajaxComment').remove();
	$('.commentPager').first().removeClass('commentBox');
	$('.commentPager').first().html(getAjaxLoadingGif());
	close('.newComment');
	
	try {
		var query = 'ajax=true&method=showComments&data=' + hash + '&status=' + start;
		jQuery.ajax({
            type: 'GET',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            url: 'public/ajax/get',            
            data: query,
            success:function(response) {
            	$('.commentPager').first().remove();            	
            	$('.commentList').first().html($('.commentList').first().html() + response);
            	show('.newComment');
            	prepare();
            },
            error:function (xhr, ajaxOptions, thrownError) {
            	$('.commentPager').first().remove();
            	show('.newComment');
            	showError(localized['shareError']);
            }    
        });	
	} catch (e) {
		$('.commentPager').first().remove();
		show('.newComment');
		showError(localized['shareError']);
	}
}

function saveComment(hash) {
	var commentAreaId = '#twt'+hash+' .commentTextArea:last';
	var commentListId = '#twt'+hash+' .commentList:last';
	var commentSubmitId = '#twt'+hash+' .button:last';
	var comment = $(commentAreaId).val();
	
	if (comment == '') {
		return;
	}
	
	$(commentAreaId).attr('disabled','disabled');
	$(commentSubmitId).attr('disabled','disabled');
	
	try {
		var query = 'ajax=true&method=shareComment&data=' + hash + '&info=' + encodeURIComponent(comment) + '&timestamp=' + Number(new Date());
		
		jQuery.ajax({
            type: 'POST',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            url: 'community/ajax/post',            
            data: query,
            success:function(response) {
            	$(commentAreaId).val('');
            	resetComment($(commentAreaId));
            	$(commentListId).html($(commentListId).html()+response);
            	$(commentAreaId).attr('disabled','');
            	$(commentSubmitId).attr('disabled','');
            	prepare();
            },
            error:function (xhr, ajaxOptions, thrownError) {
            	$(commentAreaId).attr('disabled','');
            	$(commentSubmitId).attr('disabled','');
            	showError(localized['shareError']);
            }    
        });			
	} catch (e) {
    	$(commentAreaId).attr('disabled','');
    	$(commentSubmitId).attr('disabled','');
    	showError(localized['shareError']);
	}
}

function resetComment(element) {		
	if (element.val() == '' || element.val() == localized['addComment']) {
		element.val(localized['addComment']);
		close(element.parent().children('img'));
		close(element.parent().children('input'));
		element.css('width','330px');
	}
}

function prepareComment(element) {
	if (element.parent().children('img').css('display') == 'none') {
		element.val('');
		element.css('width','340px');
		element.parent().children('img').show('bounce');
		element.parent().children('input').show('drop');
	}
}

function editPrwTitle() {
	var value = $('#prwTitle').text();
	$('#prwTitle').unbind('click');
	$('#prwTitle').html('<input id="prwTitleEdit" type="text" value="'+value+'"/>');
	$('#prwTitleEdit').blur(editPrwTitleDone);
}

function editPrwTitleDone() {
	if ($('#prwTitleEdit') == null) { return; }
	var value = $('#prwTitleEdit').val();
	$('#prwTitle').html(value);
	$('#prwTitle').click(editPrwTitle);
}

function editPrwDesc() {
	var value = $('#prwDesc').text();
	$('#prwDesc').unbind('click');
	$('#prwDesc').html('<textarea id="prwDescEdit">'+value+'</textarea>');
	$('#prwDescEdit').blur(editPrwDescDone);
}

function editPrwDescDone() {
	if ($('#prwDescEdit') == null) { return; }
	var value = $('#prwDescEdit').val();
	$('#prwDesc').html(value);
	$('#prwDesc').click(editPrwDesc);
}

function cancelPreview() {
	$('#sharePreview').hide();	
	$('#sharePreview').html('');
	$('#share').val(localized['shareText']);
	$('#share').css('height', '25px');
	$('#tagField').val(localized['tagAddInfo']);
	$('#shareOptions').hide();
	$('#shareButton').hide();
	$('#tagZone').html('');
	setData('#contentData', 'preview-id', "");
}

function closePreview() {
	var id = '#'+getData('#contentData', 'preview-id');
	hide(id);
	setTimeout("$('"+id+"').remove();", 500);
	cancelPreview();
}

function loadImageDone() {
	++loadedImageCount;
	if (loadedImageCount == totalImageCount) {
		// set controls		
		close('#prwAjax');
		if (previewImages.length > 0) {
			if ($('#prwCtrl').css('display') == 'none') {		
				open('#prwCtrl');
			}
			updatePreviewImageCounter();
			$('#prwSw').click(switchPreview);
			$('#prwPr').click(previewPrevious);
			$('#prwNx').click(previewNext);
			$('#prwImgPrnt').bind("contextmenu", function(e) {
		        return false;
			}); 
			$('#prwImgPrnt').mousedown(function(event) {
			    switch (event.which) {
			        case 1:  
			            previewNext();
			            break;
			        case 3:
			            previewPrevious();
			            break;
			    }    
			});					
		} else {
			close('#prwImgPrnt');
		}
	} 	
}

function updatePreviewImageCounter() {
	$('#prwPg').text('(' + (currentImage + 1) + '/' + previewImages.length + ')');
}

function previewNext() {
	currentImage++;
	if (currentImage > previewImages.length-1) {
		currentImage = 0;
	}
	previewImage();
}

function previewPrevious() {
	--currentImage;
	if (currentImage < 0) {
		currentImage = previewImages.length-1;
	}
	previewImage();
}

function switchPreview() {
	if ($('#prwImgPrnt').css('display') == 'block') {
		close('#prwImgPrnt');
		$('#prwPr').css('visibility', 'hidden');
		$('#prwNx').css('visibility', 'hidden');
		$('#prwPg').css('visibility', 'hidden');
		
	} else {
		open('#prwImgPrnt');
		$('#prwPr').css('visibility', 'visible');
		$('#prwNx').css('visibility', 'visible');
		$('#prwPg').css('visibility', 'visible');		
	}
}

function arrangeImageSize(id) {
	if ($(id).height() >= $(id).width()) {
		$(id).css('width', '');
		$(id).css('height', '80px');
	} else {
		$(id).css('width', '80px');
		$(id).css('height', '');
	}
	$('#prwImg').css('visibility', 'visible');
}

function previewImage() { 
	var img = previewImages[currentImage];
	if (img == null) return;
	loadThumbnail(img.src);
	updatePreviewImageCounter();
}

function loadThumbnail(src) {
	$('#prwImg').css('visibility', 'hidden');
	$('#prwImg').attr('src', src);
	$('#prwImg').load(function() {
		$('#prwImg').css('margin', '5px');
		arrangeImageSize('#prwImg');
	});
}

function loadImages() {
	// eval data
	var json = $('#prwData').html();
	var images = eval(json);
	$('#prwData').remove();	
	// load images
	totalImageCount = images.length;
	loadedImageCount = 0;
	currentImage = 0;
	previewImages = new Array();
	for (var i = 0; i < images.length; i++) { 
		var img = new Image(); 
		img.src = images[i];
		img.onerror = function() {
			loadImageDone(); 
		};    
		img.onload = function() {								
			loadImageDone();
			if (this.width > 50 && this.height > 50) {
				previewImages[previewImages.length] = this;
				if (loadedImageCount > 0 && $('#prwImg').attr('preview') == 'true') {						
					$('#prwImg').attr('preview', 'false');
					setTimeout("previewImage();", 750);					
				}	
			} 			
		}; 
	}
	open('#prwAjax');			
}

function showError(error) {
	$('#errorMsg').text(error);
	scroll(0,0);
	display('#error');
}

function showHideStatus(mode) {
	if (mode) {		
		$('#shareBox').show();
		$('#loading').hide();		
	} else {
		$('#shareBox').hide();
		$('#loading').show();
	}
}

function shareText() { 
	// validate
	if (getData('#contentData', 'preview-id') == '' && $('#share').val() == '') {
		showError(localized['errorEmpty']);
		return;
	} else if (getData('#contentData', 'preview-id') == '' && $('#share').val().length > 1024) {
		showError(localized['errorMax']);
		return;
	} 	
	
	if (getData('#contentData', 'preview-id') != '') {
		if ($('#prwUrl').attr('title') == '') {
			$('#prwUrl').attr('title', $('#shareItem').val());	
		}
		shareAjax('shareLink');	
	} else {
		shareAjax('shareText');
	}
}

function previewLink() {
	if ($('#shareItem').val() == '') {
		showError(localized['errorEmpty']);
		return;
	}  		
	shareAjax('previewLink');
}

function shareLink() {
	if ($('#shareItem').val() == '') {
		showError(localized['errorEmpty']);
		return;
	}  		
	shareAjax('shareLink');
}

function showAjaxError() {
    showError(localized['errorGeneral']);
	showHideStatus(true);
}

function previewContent() {
	$('#tagZone').show();
	$('#sharePreview').html(ajaxResponse);	
	$('#sharePreview').show();	
 	if (getData('#contentData', 'preview-id') == '') {		
		appendContent();				
	} else {
		if ($('#share').val() == $('#prwUrl').attr('title')) {
			$('#share').val('');
			$('#share').css('height', '25px');
		}		
		showHideStatus(true);
		$('#shareButton').show();
		$('#prwClose').click(cancelPreview);
	}
}

function appendContent() {
	$('#sharePreview').hide();	
	var id = 'cnt' + Number(new Date());
	$('#ajaxContent').html('<div id="'+id+'" class="ncnt"></div>' + $('#ajaxContent').html());
	var content = $('#sharePreview').html();
	$('#'+id).html(content);
	showHideStatus(true);
	$('#'+id).show('blind');
	$('#sharePreview').html('');
	$('#share').val(localized['shareText']);
	$('#share').css('height', '25px');
	$('#tagField').val(localized['tagAddInfo']);
	$('#shareOptions').hide();
	$('#shareButton').hide();
	$('#tagZone').html('');
	setData('#contentData', 'preview-id', '');
	prepare();
}

function closeVideoCallback(hash) {
	$('#twt'+hash+' .twtTextInfo').show();
	$('#twt'+hash+' .twtTextPic').show();		
	$('#twt'+hash+' .twtClose').hide();
}

function closeVideo(hash) {
	$('#twt'+hash+' .twtVideo').html('');
	$('#twt'+hash+' .twtVideo').hide('clip');
	setTimeout('closeVideoCallback("'+hash+'")',500);
}

function showVideo(item) {
	var hash = item.attr("data-video-hash");
	$('#twt'+hash+' .twtTextInfo').hide();
	$('#twt'+hash+' .twtTextPic').hide();
	$('#twt'+hash+' .twtVideo').show('clip');
	setTimeout('loadVideo("'+hash+'")', 500);
}

function loadVideo(hash) {
	$('#twt'+hash+' .twtVideo').html(getAjaxLoadingGif());
	try {
		jQuery.ajax({
            type: 'GET',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            url: 'public/ajax/get', 
            data: 'ajax=true&method=showVideo&data='+hash,
            success:function(response) {
            	$('#twt'+hash+' .twtVideo').html(response);
            	$('#twt'+hash+' .twtClose').show();
            },
            error:function (xhr, ajaxOptions, thrownError) {
            	showAjaxError();
            }    
		});
	} catch (e) {
		showAjaxError();
	}
}

function playAudio(hash, url, type) {
	var audioId = '#audio'+hash;
	var iconId = audioId + ' .audioIcon';
	var spanId = audioId + ' .audioSpan';
	
	var classes = $(iconId).attr('class');
	if (classes.indexOf('ui-icon-volume-on') > -1) {
		$(iconId).removeClass('ui-icon-volume-on');
		$(iconId).addClass('ui-icon-volume-off');
		$(spanId).html('<embed onload="alert(\"yuklendi!\")" height="30" autoplay="true" autostart="true" src="'+url+'" type="'+type+'"></embed>');
	} else {
		$(iconId).removeClass('ui-icon-volume-off');
		$(iconId).addClass('ui-icon-volume-on');
		$(spanId).html('');
	}
}

function shareAjax(method) {
	editPrwTitleDone();
	editPrwDescDone();
	showHideStatus(false);
	$('.searchResult').first().hide();
	$('#sbp').hide('blind');
	$('#shareOptions').hide();
	$('#shareButton').hide();
	$('#tagZone').hide();
	$('#shareDetails').hide('blind');
	
	try {		
		var query = 'ajax=true&tags=' + getSerializedTags() + '&method=' + method + '&info=' + encodeURIComponent($('#share').val()) + '&timestamp=' + Number(new Date());
		if (method == 'shareLink') {
			query = query + '&data=' + encodeURIComponent($('#prwUrl').attr('title'));
			if ($('#prwImgPrnt').css('display') != 'none') {
				query = query + '&thumbnail=' + encodeURIComponent($('#prwImg').attr('src'));
			}
		} else {			
			query = query + '&data=' + encodeURIComponent($('#shareItem').val());
		}	 
		if (getData('#contentData', 'preview-id') != '') { 
			if ($('#prwTitle') != null) {
				query = query + '&title=' + encodeURIComponent($('#prwTitle').text());	
			}
			if ($('#prwDesc') != null) {
				query = query + '&desc=' + encodeURIComponent($('#prwDesc').text());	
			}
		}

		jQuery.ajax({
            type: 'POST',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            url: 'community/ajax/post', 
            data: query,
            success:function(response) {   
            	ajaxResponse = response;
            	previewContent();
            },
            error:function (xhr, ajaxOptions, thrownError) {
            	if (getData('#contentData', 'preview-id') != '') { 
            		$('#shareDetails').show(); 
            	}
            	showAjaxError();
            }    
        });			
	} catch (e) {
    	if (getData('#contentData', 'preview-id') != '') { 
    		$('#shareDetails').show(); 
    	}
		showAjaxError();
	}
}

function shareFocus() {
	if (getData('#contentData', 'preview-id') == '' && $('#share').val() == localized['shareText']) {
		$('#share').val('');
	}
	if ($('#sbp').css('display') == 'none') {
		if (getData('#contentData', 'preview-id') == '') {
			if ($('#shareOptions').css('display') == 'none') {
				$('#shareOptions').show();					
				$('#shareButton').show();	
				addTagButton();
			}
		} 
	}
} 

function showImageShare() {
	$('#shareType').val('image');
	$('#shareItem').val('http://');
	$('#sbpTopIcon').attr('class','shareIcon ui-icon ui-icon-image');
	$('#sbpTitle').text(localized['sbpImageTitle']);
	$('#sbpInfo').text(localized['sbpImageInfo']);
	$('#sbpFromFile').show();
	
	$('#shareOptions').hide();
	$('#shareButton').hide();
	$('#sbp').show('blind');
}

function showVideoShare() {	
	$('#shareType').val('video');
	$('#shareItem').val('http://');
	$('#sbpTopIcon').attr('class','shareIcon ui-icon ui-icon-video');
	$('#sbpTitle').text(localized['sbpVideoTitle']);
	$('#sbpInfo').text(localized['sbpVideoInfo']);
	$('#sbpFromFile').show();
	
	$('#shareOptions').hide(); 
	$('#shareButton').hide();
	$('#sbp').show('blind');
}

function showLinkShare() {
	$('#shareType').val('link');
	$('#shareItem').val('http://');
	$('#sbpTopIcon').attr('class','shareIcon ui-icon ui-icon-link');
	$('#sbpTitle').text(localized['sbpLinkTitle']);
	$('#sbpInfo').text(localized['sbpLinkInfo']);
	$('#sbpFromFile').show();
	
	$('#shareOptions').hide();
	$('#shareButton').hide();
	$('#sbp').show('blind');
}

function twtFocus(item) {
	if (getData('#contentData', 'single-content') != 'true') {
		item.css('background-color', '#f8f8f8');
	}
}

function twtBlur(item) {
	if (getData('#contentData', 'single-content') != 'true') {
		item.css('background-color', '#fff');	
	}
}

function cbFocus(item) {
	var subItem = item.children('.commentRemove').first();
	if (subItem != null && subItem.css('visibility') == 'hidden') {
		subItem.css('visibility','visible');
	}
}

function cbBlur(item) {
	var subItem = item.children('.commentRemove').first();
	if (subItem != null && subItem.css('visibility') == 'visible') {
		subItem.css('visibility','hidden');
	}
}
 
function hideShare() {
	$('#sbp').hide('puff'); 
	$('#share').text(localized['shareText']);
	$('#share').css('height', '25px');
	$('#tagZone').html('');
	$('#tagField').val(localized['tagAddInfo']);
}

function showNewsGroup(target) {
	if ($(target).css('display') == 'none') {
		$('.newsGroup').hide();
		showE(target, 'slide');
	}
}

function extractUrl(data) {
	var e=/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;	
    if (data.match(e)) {
        return {url: RegExp['$&'],
                protocol: RegExp.$2,
                host:RegExp.$3,
                path:RegExp.$4,
                file:RegExp.$6,
                hash:RegExp.$7}; 
    }  
    return null;
}

function checkStatus(element)
{
	if (element.value.length > userInput.length + 6) {
		var url = extractUrl(element.value);
		if (url != null) {			
			$('#shareItem').val(url.url);
			element.value = element.value.replace(url.url, '');
			saveLink(true);
		}
	}
	userInput = element.value;	
}

function getTimeElapsed(time)
{
	var SECOND_IN_MILLIS = 1000;
	var MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
	var HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
	var DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
	var YEAR_IN_MILLIS = DAY_IN_MILLIS * 365;

	var now = new Date().getTime();
	var diff = now - time;
	
	var elapsedYears = Math.floor(diff / YEAR_IN_MILLIS);
	diff = diff % YEAR_IN_MILLIS;
	var elapsedDays = Math.floor(diff / DAY_IN_MILLIS);
	diff = diff % DAY_IN_MILLIS;
	var elapsedHours = Math.floor(diff / HOUR_IN_MILLIS);
	diff = diff % HOUR_IN_MILLIS;
	var elapsedMinutes = Math.floor(diff / MINUTE_IN_MILLIS);

	var buffer = '';
	if (elapsedYears > 0) {
		buffer += elapsedYears + ' ' + localized['global.year'] + ' ';
	}
	if (elapsedDays > 0) {
		buffer += elapsedDays + ' ' + localized['global.day'] + ' ' + localized['global.day'];
	}
	if (elapsedYears == 0 && elapsedDays == 0 && elapsedMinutes > 0) {
		buffer += elapsedMinutes + ' ' + localized['global.minute'] + ' '; 
	}
	if (elapsedYears == 0 && elapsedDays == 0 && elapsedMinutes == 0) {
		buffer += '~1 ' + localized['global.minute'];
	}
	return buffer.trim();
}

function enableScrollUpdate() {
	$(window).scroll(function() {
        if (scrolled && $(window).scrollTop() == $(document).height() - $(window).height()){
       	   showContents();
        } else if (!scrolled) {
        	scroll(0,0);
        }
        scrolled = true;
	});
}

function prepareSearch(searchText, info) {
	var element = $('#searchform .textbox').first();
	var value = info;
	if (searchText !== '') {
		value = searchText;
		element.css('color', '#777');
	}
	element.val(value);
	element.click(function(){
		element.css('color', '#777');
		if (element.val() == info) {
			element.val('');
		}
	});
}

function fileUploadAjaxStatus(status) {
	if (status) {
		$('.ajaxButton').hide();
		$('#tmbRemove').hide();
		$('.videoLoading').show();		
	} else {
    	$('.ajaxButton').show();
    	$('#tmbRemove').show();
    	$('.videoLoading').hide();
	}
}

function removePicture() {
	fileUploadAjaxStatus(true);
	try {
		var query = 'ajax=true&method=removePicture&data=' + Number(new Date());
		jQuery.ajax({
            type: 'POST',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            url: 'community/ajax/post',            
            data: query,
            success:function(response) {
            	$('#tmb').attr('src', response + '?noCache=' + Number(new Date()));
            	fileUploadAjaxStatus(false);
            },
            error:function (xhr, ajaxOptions, thrownError) {
            	showError(localized['shareError']);
            	fileUploadAjaxStatus(false);
            }    
        });	
	} catch (e) {
		showError(localized['shareError']);
		fileUploadAjaxStatus(false);
	}
}

function ajaxFileUpload()
{
	fileUploadAjaxStatus(true);
    $.ajaxFileUpload({
            url: 'community/ajax/upload',
            secureuri: false,
            fileElementId: 'file',
            dataType: 'json',
            success: function (data, status) {
            	if (data.error == '') {
            		$('#tmb').attr('src', data.msg + '?noCache=' + Number(new Date()));
            		$('#file').val('');
            	} else {
            		if (data.msg == 'error.invalid.format') {
            			showError(localized['errorInvalidFormat']);
            		} else if (data.msg == 'error.file.not.found') {
            			showError(localized['errorFileNotFound']);
            		} else if (data.msg == 'error.file.size') {
            			showError(localized['errorFileSize']);
            		} else {
            			showError(localized['errorGeneral']);	
            		}
            	}
            	fileUploadAjaxStatus(false);
            },
            error: function (data, status, e) {
            	showError(localized['errorGeneral']);
            	fileUploadAjaxStatus(false);
            }
        });
    return false;
} 

function prepare() {
	$('.tooltipx').tooltip({ effect: 'slide'});
	$('.lbox').lightBox({fixedNavigation:false});	
	$('.shareIcon').mouseover(function(){mouseOver($(this));});
	$('.shareIcon').mouseout(function(){mouseOut($(this));});
	$('.twt').mouseover(function(){twtFocus($(this));});
	$('.twt').mouseout(function(){twtBlur($(this));});
	$('.twtZoomIn').click(function(){twtZoomIn($(this));});
	$('.commentBox').mouseover(function(){cbFocus($(this));});
	$('.commentBox').mouseout(function(){cbBlur($(this));});
	$('.commentRemove').click(function(){removeComment($(this));});
	$('.twtRemove').click(function(){removeShare($(this));});
	$('#share').val(localized['shareText']);
	$('.videoLink').click(function(){showVideo($(this));});
	$('.commentTextArea').focus(function(){prepareComment($(this));});
	if (getData('#contentData', 'single-content') == 'true') {
		twtShowAll($('.twtZoom').first());
	}
	backgroundAnim();
}

$(function() {	
	prepare();	
});

/*
 * jQuery autoResize (textarea auto-resizer)
 * @copyright James Padolsey http://james.padolsey.com
 * @version 1.04
 */

(function(a){a.fn.autoResize=function(j){var b=a.extend({onResize:function(){},animate:true,animateDuration:150,animateCallback:function(){},extraSpace:20,limit:1000},j);this.filter('textarea').each(function(){var c=a(this).css({resize:'none','overflow-y':'hidden'}),k=c.height(),f=(function(){var l=['height','width','lineHeight','textDecoration','letterSpacing'],h={};a.each(l,function(d,e){h[e]=c.css(e)});return c.clone().removeAttr('id').removeAttr('name').css({position:'absolute',top:0,left:-9999}).css(h).attr('tabIndex','-1').insertBefore(c)})(),i=null,g=function(){f.height(0).val(a(this).val()).scrollTop(10000);var d=Math.max(f.scrollTop(),k)+b.extraSpace,e=a(this).add(f);if(i===d){return}i=d;if(d>=b.limit){a(this).css('overflow-y','');return}b.onResize.call(this);b.animate&&c.css('display')==='block'?e.stop().animate({height:d},b.animateDuration,b.animateCallback):e.height(d)};c.unbind('.dynSiz').bind('keyup.dynSiz',g).bind('keydown.dynSiz',g).bind('change.dynSiz',g)});return this}})(jQuery);

