var xmlhttp=false;
var timer = 300;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	try {
		xmlhttp = new XMLHttpRequest();
	} catch (e) {
		xmlhttp=false;
	}
}
if (!xmlhttp && window.createRequest) {
	try {
		xmlhttp = window.createRequest();
	} catch (e) {
		xmlhttp=false;
	}
}

function close_tab(tab_name) {
    jQuery('#'+tab_name).hide("slow");
}
function open_tab(tab_name) {    
    jQuery('#'+tab_name).show("slow");
}
function toggle_tab(tab_name) {
	jQuery('#'+tab_name).toggle("slow");
}
function check_tab(tab_name) {
	if (document.getElementById(tab_name).style.display == 'none') {
		open_tab(tab_name);
	} else {
		close_tab(tab_name);
	}
}

function closeMessage() {
	$('div.error').hide().remove();
	$('div.good').hide().remove();
}

function changeTabStaff(openTab) {
	var listTab = new Array(
		'Wallpaper',
		'Textures',
		'Architecture',
		'Nature',
		'Technic',
		'Food',
		'Other'
	);
	for (var i=0; i<listTab.length; i++) {
		if (document.getElementById(listTab[i])) {
			if (openTab == listTab[i]) {
				document.getElementById(openTab).style.display = 'block';
				document.getElementById('li_'+openTab).className = 'active';
			} else {
				document.getElementById(listTab[i]).style.display = 'none';
				document.getElementById('li_'+listTab[i]).className = '';
			}
		}
	}
}

/* Begin list Tabs */
$.changeTabNew = function () {
	var newTab;		
	$.changeListTabs = function (newTab) {
		$('div.tab_panel ul li').attr('class','');
		$('div.box_files, div.list_side_files, div.purchase_block, div.box_files_staff').css('display','none');
		$('div.tab_panel ul li:eq('+newTab+')').attr('class','active');
		$('div.box_files:eq('+newTab+'), div.list_side_files:eq('+newTab+'), div.purchase_block:eq('+newTab+'), div.box_files_staff:eq('+newTab+')').css('display','block');	
	}
	if ($('.tab_panel').is('.static')) {
		//alert('bad');
		//return true;
	} else if ($('div.tab_panel')) {
		if (location.hash) {
			newTab = $('div.tab_panel ul li').index($('a[rel='+location.hash.replace(/^#/,'')+']').parent('li'));
		} else {
			newTab = 0;
		}
		$.changeListTabs(newTab);
		$('div.tab_panel ul li').click(function () {
			newTab = $('div.tab_panel ul li').index(this);
			$.changeListTabs(newTab);
			return false;
		});
	}	
}

$(function () {
	$.changeTabNew();
});
/* END list Tabs */

function blockButton(name) {
	if (document.getElementById(name)) {
		document.getElementById(name).style.display = 'none';
	}	
}

function editRequestPayment(name) {
	if (document.getElementById(name).disabled) {
		document.getElementById(name).disabled = false;
		open_tab('form_'+name);
		close_tab('text_'+name);
	} else {
		document.getElementById(name).disabled = true;
		close_tab('form_'+name);
		open_tab('text_'+name);
	}
}

function open_banner(afiliate_id) {
	for (var i = 1; i <= 7; i++) {
		if (afiliate_id == i) {
			open_tab('banner_'+i);
		} else {
			close_tab('banner_'+i);
		}
	} 
}

function SendMessage() {
	toggle_tab('SendMessage');
}

function ActionSendMessage() {
	var error = new Boolean();
	error = false;
	var user_email = document.getElementById('user_email').value;
	var user_name = document.getElementById('user_name').value;
	var user_message = document.getElementById('user_message').value;
	var action_message = document.getElementById('action_message').value;
	var page_message = document.getElementById('page_message').value;
	var message_user_id = document.getElementById('message_user_id').value;
	if (user_email == '') error = true;
	if (user_name == '') error = true;
	if (user_message == '') error = true;
	
	if (error) {
		alert ("Error\nNot all the files filled.");
	} else {
		toggle_tab('SendMessage');
		AjaxSendMessage(user_email,user_name,user_message,action_message,page_message,message_user_id);
	}
}

function go_to_link (newlink) {
	location = newlink;
}

/*
function changeCategory (categoryName) {
	var subcategoryId = document.getElementById('filter_category').value;
	for(i = document.getElementById('filter_category').options.length-1; i > 0; i--) {
		if (document.getElementById('filter_category').options[i].value == subcategoryId) {
			var subcategoryText = document.getElementById('filter_category').options[i].text;
		}
	} 	
	if (subcategoryId == 0) {
		newlink = '/'+categoryName+'.html';
	} else {
		newlink = '/'+subcategoryText.replace(/ /g,'-')+'/'+categoryName+'-Category'+subcategoryId+'.html';
	}
	go_to_link (newlink);
}
*/

function check_password (tab_name) {
	if (document.getElementById('password_tab_check').style.display == 'block') {
		close_tab('password_tab_check');
	}
	if (document.getElementById(tab_name).style.display == 'none') {
		document.getElementById('edit_password').value = '';
		document.getElementById('edit_password').disabled = false;
		document.getElementById('edit_confirm_password').value = '';
		document.getElementById('edit_confirm_password').disabled = false;
		open_tab(tab_name);
	} else {
		document.getElementById('edit_password').value = '';
		document.getElementById('edit_password').disabled = true;
		document.getElementById('edit_confirm_password').value = '';
		document.getElementById('edit_confirm_password').disabled = true;
		close_tab(tab_name);
	}
}

function checkUploadFile() {
	error = false;
	if ((document.getElementById('approved_images_th_hidden').value == '') || (document.getElementById('approved_preview_source_hidden').value == '') || (document.getElementById('approved_preview_source_swf_hidden').value == '') || (document.getElementById('approved_source_files_hidden').value == ''))
	error = true;
	if (document.getElementById('preview_at_fullscreen').checked && document.getElementById('approved_preview_files_hidden').value == '') 
	error = true;
	
	if (error) { 
		returnValue = false;
		alert ("Error\nNot all the files filled.");
	} else 
		returnValue = true;
}

function changePreviewFlash() {
	if (document.getElementById('preview_at_fullscreen').checked) {
		$('#block_is_not_full_screen').slideUp('',function(){$('#block_is_checked_full_screen').slideDown()});		
	} else {
		$('#block_is_checked_full_screen').slideUp('',function(){$('#block_is_not_full_screen').slideDown()});		
	}
}

function forgotPassword() {
	toggle_tab('forgot_name_form');
}
function forgotUserName() {
	toggle_tab('forgot_pass_form');
}

/* Begin Reply comment User */
function replyToThisUser(postId) {
	if ($('#User_'+postId)) {
		var UserName = $('#User_'+postId).html();
		var CommentText = $('#comment_text');
		CommentText.value = 'To '+UserName+': ';
		$('#replyUser').val($('#replyUser'+postId).val());
		$('#replyUserLogin').val($('#replyUserLogin'+postId).val());
		$("#cancel_Reply").show();
		$(".title_comment").hide();
		$("#reply_to_user").html(UserName);
		$(".title_reply_comment").show(); 
	}
}

function cancelReply() {
	$("#cancel_Reply").hide();
	$("#comment_text").val('');
	$("#replyUser").val('');
	$("#replyUserLogin").val('');
	$(".title_comment").show();
	$(".title_reply_comment").hide();
}
/* End Reply comment User */

function AjaxSendMessage(user_email,user_name,user_message,action_message,page_message,message_user_id) {
	user_email = user_email.replace(/'/,"\'");
	user_name = user_name.replace(/'/,"\'");
	user_message = user_message.replace(/'/,"\'");
	
	var url =       '/index.html';
	var params =    'user_email='+user_email+'&user_name='+user_name+'&user_message='+user_message+'&page='+page_message+'&action='+action_message+'&user_id='+message_user_id;
	
	xmlhttp.open("POST", url, true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.send(params);
	xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			document.getElementById('body_page').innerHTML = xmlhttp.responseText + document.getElementById('body_page').innerHTML;
			open_tab('resultMessage');
		}
	}
}

function checkEarning() {
	var earning = new Number();
	var earning_convert = new Number();
	earning = parseFloat(document.getElementById('earning').innerHTML);
	earning_convert = parseFloat(document.getElementById('earning_convert').value);
	if (earning_convert < 1.00) {
		alert('Earning ballance has to be 1$ or more');
		returnValue = false;
	} else if (earning < earning_convert) {
		alert("You 'earning' ballance is to low - ("+earning+")");
		returnValue = false;
	} else if (confirm('Are You sure you want to convert your earning ballance?')) {
		returnValue = true;
	} else {
		returnValue = false;
	}
}

function formatNumber(num) {
	num="" + Math.floor(num*100.0 + 0.5)/100.0;
	var i=num.indexOf(".");
	if ( i<0 ) num+=".00";
	else {
		num=num.substring(0,i) + "." + num.substring(i + 1);
		i=(num.length - i) - 1;
		if ( i==0 ) num+="00";
		else if ( i==1 ) num+="0";
		else if ( i>2 ) num=num.substring(0,i + 3);
	}
	return num;
}

function PreviewDescription(vars) {
	vars = vars ? vars : 'upload_description';
	var descriptionPreview = document.getElementById(vars);	
	if (descriptionPreview.value) {
		processDescription(descriptionPreview.value);
	} else {
		close_tab('PreviewBlock');
	}
}	

function processDescription(Text) {
	Text = Text.replace(/'/,"\'");	
	$('#PreviewBlock').slideUp();
	$.post("/", {description:Text, page:'preview_description', ajax:"action"}, 
	  function(data) {
		if (data.status == 'error') {
			$('#previewDescription').html(data.status_message);
			$('#PreviewBlock').slideDown();
		} else {
			$('#previewDescription').html('<p>'+data.result+'</p><div class="clr"></div>');
			$('#PreviewBlock').slideDown();
		}
	  }, "json");
}

/*
 * Url preview script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
 
this.screenshotPreview = function(){	
	/* CONFIG */

	xOffset = 10;
	yOffset = 20;
		
	// these 2 variable determine popup's distance from the cursor
	// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.screenshot").hover(function(e){
		
		var objImage = new Image();
		this.t = this.title;
		this.title = "";
		var c = '';
		//var c = (this.t != "") ? "<br/><span style='font:normal 12px Arial;'>" + this.t + "</span>" : "";
		$("body").append("<p id='screenshot'><img src='/images/spacer.gif' alt='" + this.t + "' id='ImagesScreen' />"+ c +"</p>");
		
		//objImage.onload = function () {
		//	document.getElementById('ImagesLoader').style.display = 'none';
		//	$('#ImagesScreen').fadeIn("fast");
		//}
		objImage.src = this.rel;
		document.getElementById('ImagesScreen').src = objImage.src;

		coo_ar=coo(e).split(",");
		top_pos=coo_ar[1];
		left_pos=coo_ar[0];
		$("#screenshot")
			.css("top",top_pos + "px")
			.css("left",left_pos + "px")
			.fadeIn("fast");						
		},
		function(){
			this.title = this.t;
			document.getElementById('ImagesScreen').style.display = 'none';
			$("#screenshot").remove();			
		});	
	
	$("a.screenshot").mousemove(function(e){
		coo_ar=coo(e).split(",");
		top_pos=coo_ar[1];
		left_pos=coo_ar[0];
		$("#screenshot")
			.css("top",top_pos + "px")
			.css("left",left_pos + "px");
	});			
};


// starting the script on page load
$(function () {
	screenshotPreview();
});

function coo(e){
	var x,y,left_pos,top_pos;
	x = (document.all) ? window.event.x + document.body.scrollLeft : e.pageX;
	y = (document.all) ? window.event.y + document.body.scrollTop  : e.pageY;
	
	if(navigator.appName.indexOf('Microsoft') != -1) {
		left_pos = ((x + 620) < document.body.clientWidth) ? (x + 30) : (x - 620);
		top_pos = ((y + 300) < (document.body.clientHeight+document.documentElement.scrollTop)) ? (y - 50) : (y - 340);
	} else {
		left_pos = ((x + 620) < window.innerWidth) ? (x + 30) : (x - 620);
		top_pos = ((y + 300) < (window.innerHeight+window.pageYOffset)) ? (y - 50) : (y - 340);
	}
	return left_pos+","+top_pos+","+x+","+y;
}

function countdown() {
 if ((0 <= 100) || (0 > 0)) {
  timer--;
  if(timer == 0) {
	document.getElementById("timer").innerHTML = '00:00';
	go_to_link(location);
  }
  if(timer > 0) {
	var minutes = Math.floor(timer / 60);
	var seconds = timer % 60;
	if (minutes<=9) minutes="0"+minutes
	if (seconds<=9) seconds="0"+seconds
	document.getElementById("timer").innerHTML = minutes+':'+seconds;
	setTimeout('countdown()',1000);
  }
 }
}

//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

// Hover Slide on Big Preview
$(function () {
	$('div#hoverSlide').hover(
	  function(){
		$('#hoverScreen').css({'top':($('#FullScreenPreview').height()-70)+'px'});
		$('#hoverScreen').fadeIn('fast');
	  }, 
	  function(){
		$('#hoverScreen').fadeOut();
	  });
});

// delete Files
function delete_user_files(id_product) {
	$.post("/index.html", {ajax: "action", proudct_id: id_product, files: "delete", page: "ajax_delete_files"}, 
	  function(data) {
		//alert("Data Loaded: " + data.php_message);
		if (data.php_message == 'Delete') {
                        $("#status_"+id_product).html('<img align="absmiddle" src="/images/removed_icon.png" alt="Removed" title="Removed"/>');
			$('#action_'+id_product).html('');
		}
	  }, "json");
}

// Purchase tabs
/*
$(function () {
	var myFile = document.location.toString();
	if (!$('input:notwork')) {
		if (myFile.match('#')) { // the URL contains an anchor
			// click the navigation item corresponding to the anchor
			var myAnchor = '#' + myFile.split('#')[1];		
			$('.tab_panel ul li a[href="' + myAnchor + '"]').click();
		} else {
			// click the first navigation item
			$('.tab_panel ul li:first').children('a').click();
		}
	}
});
*/


// onload function
$(function(){
	// slide network menu
	$('a[rel=network]').click(function() {
		$('#network').slideToggle("slow");
		return false;
	});		
	
	// slide navigation menu
	$('ul.menu_main li').each(function() {
		if ($('a',this).text() == 'Make Money') { // check finish dublicate
			visible = 0;
		}
		if (visible) {
			temp += '<li>'+$(this).html()+'</li>';
			$(this).css('display','none');
			$(this).addClass('catalog_menu');
		}
		if ($('a',this).text() == 'Catalog') { // check start dublicate
			$(this).addClass('inner');
			visible = 1;
		}
	});
	$('<li class="list_Category"><div><span>'+nameCat+'</span><div><ul>'+temp+'</ul></div></li>').insertAfter('.inner');
	$(function () {checkSizeWindow()});		
	$('li.list_Category').mouseover(function() {$(this).find('ul').show()});
	$('li.list_Category div').mouseout(function() {$('.list_Category ul').hide()});
	$('li.list_Category div ul li').mouseover(function() {
		$(this).stop().animate({backgroundColor:'#181818'});
	}).mouseout(function() {
		$(this).stop().animate({backgroundColor:'#313131'});
	});		
	$(window).resize(function() {checkSizeWindow()});
	function checkSizeWindow() {
		if ($(window).width() < 1310) smallMenu(); else bigMenu();
	}		
	function smallMenu () {
		if ($('.list_Category').css('display') == 'none') {
			$('.list_Category').css('display', 'block');
			$('li.catalog_menu').css('display', 'none');
		}
	}		
	function bigMenu () {
		if ($('.list_Category').css('display') == 'block') {
			$('.list_Category').css('display', 'none');
			$('li.catalog_menu').css('display', 'block');
		}
	}
	
	// list attach files
	$('div.button_attach_files').mouseover(function () {$('div.list_attach_files').show();});
	$('div.button_attach_files').mouseout(function () {$('div.list_attach_files').hide();});
	
	// info panel comment
	$('.product_comments_post, .reply').mouseenter(function () { 
		$(this).find('.info_product_comments').stop(false, true).slideDown('fast'); 
	}).mouseleave(function () { 
		$(this).find('.info_product_comments').stop(false, true).slideUp('fast'); 
	});
	
	// report spam
	$('a[rel=report_spam]').click(function () {
		$.post('/', {postId:$(this).attr('id'), ajax:'action', page:'report_spam'}, function (data) {
			if (data.status == 'success') {
				$('div#comment_'+data.post_id).hide();
				alert(data.status_message);
			} else if (data.status == 'decline') {
				$('div#comment_'+data.post_id).hide();
				alert(data.status_message);				
			} else {
				alert(data.status_message);
			}			
		}, 'json');
		return false;
	});	

	// Ballon for earnings and download
	$('span.balloon').each(function() {
		$(this).qtip({
			content: {url: '/', data: {ajax: 'action', page: 'refaund_message', download_id: $(this).attr('title')}, method: 'post'},
			position: {corner: {target: 'bottomRight', tooltip: 'topRight'}},
			style: {padding: 5, border: 1, name: 'dark', 'font-size': 12, 'line-height': 1.4}
		});
	});	
	
	// input check all
	$("input[name=checkall]").click(function() {
		var checked_status = this.checked;
		var checked_name = this.value;
		$("."+checked_name).each(function() {
			this.checked = checked_status;
		});
	});
	
	// slide list search catagery 
	var arraySearch = new Array();	
	var searchCatFlag = false;
	var clearStr = '';
	$('.input_text_list').text(clearStr);
	$('.input_text_catalog_checkbox input').each(function () {
		arraySearch[$(this).val()] = $(this).parent('label').children('span').html();
		var checked = $(this).attr('checked'); 
		if (checked) {
			clearStr += (clearStr?', ':'')+arraySearch[$(this).val()];
			searchCatFlag = true;
		}
	});
	clearStr = clearStr.length <= 30 ? clearStr : clearStr.substr(0,27)+'...';
	$('.input_text_list').text(clearStr);
	
	$('.input_text_catalog_box').mouseleave(function () {
		$('.input_text_catalog_checkbox').slideUp('slow');
		$('.input_text_list').removeClass('active');
	});
	
	$('.input_text_catalog_box').click(function () {
		if ($('.input_text_catalog_checkbox').css('display') == 'none') {
			$('.input_text_catalog_checkbox').slideDown('fast');
			$('.input_text_list').addClass('active');
		}
	});
	$('a.input_text_list').click(function () {
		$('.input_text_catalog_checkbox').slideUp('fast');
		$('.input_text_list').removeClass('active');
	});	
	
	//$('a.input_text_list').click(function () {alert(););	
	$('.input_text_catalog_checkbox ul li').hover(function () {$(this).addClass('active');}, function () {$(this).removeClass('active');});		
	$('.input_text_catalog_checkbox input').click(function () {
		var all_true = true, all_false = true, str = '';
		if (($(this).val() == -1) && $(this).is('checked')) {
			$('.input_text_catalog_checkbox input').attr('checked',true);
		} else if (($(this).val() == -1) && $(this).not('checked')) {
			$('.input_text_catalog_checkbox input').attr('checked',true);			
		}		
		$('.input_text_list').text('');
		$('.input_text_catalog_checkbox input').each(function () {
			if ($(this).val() != -1) {
				var checked = $(this).attr('checked');
				if (checked) {
					all_true = all_true ? true : false;all_false = false;
					$('.input_text_list').append(arraySearch[$(this).val()]);
					str += (str?', ':'')+arraySearch[$(this).val()];
				} else {
					all_true = false;all_false = all_false ? true : false;					
				}
			}
		});
		
		if (all_true || all_false) {
			$('.input_text_list').text(arraySearch[-1]);
			$('.input_text_catalog_checkbox input').attr('checked',false);
			$('.input_text_catalog_checkbox input:first').attr('checked',true);
		} else {
			$('.input_text_catalog_checkbox input:first').attr('checked',false);
			str = str.length <= 30 ? str : str.substr(0,27)+'...';
			$('.input_text_list').text(str);
		}			
	});
	
	$('.input_text_search').click(function () {
		if ($('.input_text_search').val() == 'Search Files') {
			$('.input_text_search').val('');
			$('.input_text_search').blur();
			$('.input_text_search').focus();
		}
	});
	
	$('#search_button').click(function () {
		if ($('.input_text_search').val() == 'Search Files') {
			$('.input_text_search').val('');
			$('.input_text_search').blur();
			$('.input_text_search').focus();
			return false;
		} else { /* all good */ }		
	});
	
	// admin rating
	$('.admin_change_rating').change(function() {
		var pointer = $(this);
		  $.post('/',
				 {
			  		ajax: "action",
			  		page: "ajax_update_rating",
			  		set_value: $(pointer).val(),
			  		for_file: $(pointer).attr('id')
			  	 },
				 function(data){
					 
				 });
	});		
	
	// user rating
	
	$('div.users_rating img').hover(function(){
		rate = $(this).attr('alt');
		$(this).parent(0).find('img').attr('src', '/images/star_empty.jpg');
		$(this).parent(0).find('img').each(function(){
			if ($(this).attr('alt') <= rate) {
				$(this).attr('src', '/images/star.jpg');
			}
		});
	});
	
	/*$('div.users_rating img').live('hover', function(){
		rate = $(this).attr('alt');
		$(this).parent(0).find('img').attr('src', '/images/star_empty.jpg');
		$(this).parent(0).find('img').each(function(){
			if ($(this).attr('alt') <= rate) {
				$(this).attr('src', '/images/star.jpg');
			}
		});
	});*/
	
	$('div.users_rating').live('mouseout', function(){
		pointer = $(this);
		$(this).parent(0).find('img').each(function(index){
			var tmp_index = index + 1;
			if (tmp_index <= $(pointer).find('input.current_rating').val()) {
				$(this).attr('src', '/images/star.jpg');
			} else {
				$(this).attr('src', '/images/star_empty.jpg');
			}
		});
	});

	$('div.users_rating img').live('click', function(){
		selected_rate = $(this).attr('alt');
		file = $(this).parent(0).find('input[type="hidden"]').val();
		$(this).parent(0).find('input.current_rating').val(selected_rate);
		$.post(
			'/index.html',
			{
				rate: selected_rate,
				file_id: file,
				ajax: "action",
				page: "ajax_user_update_rating"
			},
			function(data){
			}
		);
	});	
	
	// public rating
	$('div.public_rating img').live('hover', function(){
		rate = $(this).attr('alt');
		$(this).parent(0).find('img').attr('src', '/images/star_empty.jpg');
		$(this).parent(0).find('img').each(function(){
			if ($(this).attr('alt') <= rate) {
				$(this).attr('src', '/images/star.jpg');
			}
		});
	});
	
	$('div.public_rating').live('mouseout', function(){
		pointer = $(this);
		$(this).parent(0).find('img').each(function(index){
			var tmp_index = index + 1;
			if (tmp_index <= $(pointer).find('input.current_public_rating').val()) {
				$(this).attr('src', '/images/star.jpg');
			} else {
				$(this).attr('src', '/images/star_empty.jpg');
			}
		});
	});

	$('div.public_rating img').live('click', function(){
		pointer = $(this);
		$('div.public_rating').die('mouseout');
		$('div.public_rating img').die('hover');
		$('div.public_rating img').die('click');
		selected_rate = parseInt($(this).attr('alt'));
		file = $('#product_id').val();
		votes = $(this).parent(0).find('input.current_votes').val();
		votes++;
		rating_sum = parseInt($(this).parent(0).find('input.rate_sum_voices').val()) + selected_rate;
		new_rate = Math.round(rating_sum / votes);
		$(this).parent(0).find('img').each(function(index){
			var tmp_index = index + 1;
			if (tmp_index <= new_rate) {
				$(this).attr('src', '/images/star.jpg');
			} else {
				$(this).attr('src', '/images/star_empty.jpg');
			}
		});
		$(this).parent(0).find('input.current_public_rating').val(new_rate);
		$(this).parent(0).find('input.current_votes').val(votes);
		$.post(
			'/index.html',
			{
				rate: selected_rate,
				file_id: file,
				ajax: "action",
				page: "ajax_public_update_rating"
			},
			function(data){
				$('div.public_rating div.vote_res').slideToggle();
				setTimeout("$('div.public_rating div.vote_res').slideToggle();", 5000);
			}
		);
	});

});

function flagit(id) {
	$.post('/', {idvalue: id, ajax: "action", page: "flag"}, function(data) {
		var box = document.getElementById('flag_'+id);
		box.className = data;
	});
}

// check all checkbox
function checkAll(type){
	//alert(type);
	var checks = document.getElementsByClassName(type); 
	for (i = 0; i < checks.length; i++) checks[i].checked = true;
}
// uncheck all checkbox
function uncheckAll(type){
	var checks = document.getElementsByClassName(type); 
	for (i = 0; i < checks.length; i++)	checks[i].checked = false;
}

// cc license choose
function license_from_radio() {
    var license = 'cc-by';
    var commercial = $('input:radio[name=cc_commercial]:checked').val();
    if (commercial == 'no') {
        license = license + '-nc';
    }
    var modification = $('input:radio[name=cc_modification]:checked').val();
    if (modification == 'no') {
        license = license + '-nd';
    } else if(modification == 'sa') {
        license = license + '-sa';
    }
    //alert(license);
    $('input:hidden[name=upload_license]').val(license);
    license_from_hidden();
}
function license_from_hidden() {
    var license = $('input:hidden[name=upload_license]').val();
    if (!license) return false;
    //alert(license);
    $('.cc-license').css('opacity', '0.2');
    $('.cc-license#'+license).css('opacity', '1');

    switch(license) {
    case 'cc-by-nc':
        $('#cc_commercial_no').attr('checked', 'checked');
        $('#cc_modification_yes').attr('checked', 'checked');
        break;
    case 'cc-by-nc-nd':
        $('#cc_commercial_no').attr('checked', 'checked');
        $('#cc_modification_no').attr('checked', 'checked');
        break;
    case 'cc-by-nc-sa':
        $('#cc_commercial_no').attr('checked', 'checked');
        $('#cc_modification_sa').attr('checked', 'checked');
        break;
    case 'cc-by-nd':
        $('#cc_commercial_yes').attr('checked', 'checked');
        $('#cc_modification_no').attr('checked', 'checked');
        break;
    case 'cc-by-sa':
        $('#cc_commercial_yes').attr('checked', 'checked');
        $('#cc_modification_sa').attr('checked', 'checked');
        break;
    case 'cc-by':
    default:
        $('#cc_commercial_yes').attr('checked', 'checked');
        $('#cc_modification_yes').attr('checked', 'checked');
        break;
    }
    //update_cc_license();
}
(function($) {
    $.fn.extend({
        isChildOf: function( filter_string ) {
            var parents = $(this).parents().get();
            for ( j = 0; j < parents.length; j++ ) {
                if ( $(parents[j]).is(filter_string) ) {
                    return true;
                }
            }
            return false;
        }
    });
})(jQuery);

$(function(){
    $('.cc-license-choose').click(license_from_radio);

    license_from_hidden();
    $('.cc-license img').click(function() {
        var license = $(this).parent().attr('id');
        //alert(license);
        $('input:hidden[name=upload_license]').val(license);
        license_from_hidden();
    });
    $('body').click(function (event) {
        //alert(event.target.nodeName);
        //alert( $(event.target).isChildOf('#donate_mb') );
        if (!$('#donate_mb_button').is(':visible') &&
            !($(event.target).isChildOf('#donate_mb')) &&
            ($(event.target).attr('id') != 'donate_mb')) {
   		    $('#donate_mb').slideUp();
   		    $('#donate_mb_button').slideDown();
        }
    });
    
    var showChar = 42;
    var ellipsestext = "...";
    var moretext = "more";
    var lesstext = "less";
    $('.more').each(function() {
        var content = $(this).html();

        if(content.length > showChar) {

            var c = content.substr(0, showChar);
            var h = content.substr(showChar-1, content.length - showChar);

            var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';

            $(this).html(html);
        }

    });

    $(".morelink").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });
    
    $("input[name='license_detail']").change(function(){
        $(this).parent().parent().find("label span").removeClass('selected');
        $(this).parent().find("label span").addClass('selected');
        $("div#license_description span").html($('#license_' + $(this).val() + '_description').val());
        $("span.detail_price").html('$' + $('#license_' + $(this).val() + '_price').val());
    });
    
    jQuery.fn.showDialog = function(type, post, options){
        var pointer = $(this);
        if (!options) {
            options = {};
        }
        var default_options = {
            width: 650
        };
        var style = '';
        $.extend(default_options, options);
        //$.extend(default_options, options);
        $.each(default_options, function(key, value) {
            style += key + ': ' + value + 'px;';
        });
        var position = $('body').position();
        var left = ($(document).width() / 2) - (default_options['width'] / 2);
        var top = position.top + 50;
        var max_height = 'max-height:' + ($(window).height() - 150) + 'px;';
        style = 'style="' + style + ' left: ' + left + 'px; top: ' + top + 'px;"';
        var title = ($(this).attr('title') != undefined) ? $(this).attr('title') : "";
        if (!type || type == 0) {
            append_str = '<div class="popupMessageWrapper" ' + style + '><div class="popupMessage"><div class="header"><span>' + title + '</span><div class="close">close <img src="/images/popup_close.png" align="absmiddle"/></div></div>';
            append_str += '<div class="message" style="' + max_height + '">' + $(this).html() + '</div>';
            append_str += '</div></div>';
            $('body').append(append_str);
        } else {
            append_str = '<div class="popupMessageWrapper" ' + style + '><div class="popupMessage"><div class="header"><span>' + title + '</span><div class="close">close <img src="/images/popup_close.png" align="absmiddle"/></div></div>';
            append_str += '<div class="message" style="' + max_height + '"><div align="center"><img src="/images/preloader.gif" alt="Loading..."/></div></div>';
            append_str += '</div></div>';
            $('body').append(append_str);
            $.post('/', post, function(data){
                 $("div.popupMessageWrapper div.message").html(data);
            });
        }
        var new_top = Math.round(($(window).height() / 2) - ($("div.popupMessageWrapper").height() / 2));
        $("div.popupMessageWrapper").css('top', new_top + 'px');
        $('embed').parent(0).css('height', $('embed').parent(0).height() + 'px');
        $('embed').css('display', 'none');
        $('object').parent(0).css('height', $('object').parent(0).height() + 'px');
        $('object').css('display', 'none');
        $("div.popupMessageWrapper div.close").live('click', function(){
            $(this).die('click');
            $("div.blockUI").die('click');
            $(document).find('div.blockUI').remove();
            $(document).find('div.popupMessageWrapper').remove();
            $('embed').parent(0).css('height', '');
            $('embed').css('display', '');
            $('object').parent(0).css('height', '');
            $('object').css('display', '');
        });
        $('body').append('<div class="blockUI"></div>');
        
        $("div.blockUI").live('click', function(){
            $(this).die('click');
            $("div.popupMessageWrapper div.close").die('click');
            $(this).remove();
            $(document).find('div.popupMessageWrapper').remove();
            $('embed').parent(0).css('height', '');
            $('embed').css('display', '');
            $('object').parent(0).css('height', '');
            $('object').css('display', '');
        });
    };
    /*jQuery.fn.hideDialog = function(){
        $(document).find('div.blockUI').remove();
        $(document).find('div.popupMessage').remove();
    }*/
    $("a.facebook").click(function(){
        $('#heager_login_popup').showDialog(0, {}, {width: 490});
        return false;
    });
});

$(function() {
  $('select#sort_by').change(function() {
    if ($('select#sort_by option:selected').val() == 'price') {
      $('#sort_by_order').val('asc');
    } else {
      $('#sort_by_order').val('desc');
    }
    this.form.submit();
  });
});
