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.box_files').slideUp('fast');
		$('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');
		//$('div.box_files:eq('+newTab+')').slideDown('fast');
	}
	if ($('.tab_panel').hasClass('.static')) {
		//alert('bad');
	} else {
		if ($('div.tab_panel').hasClass('.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');
}

function replyToThisUser(postId) {
	if (document.getElementById('User_'+postId)) {
		var UserName = document.getElementById('User_'+postId).innerHTML;
		var CommentText = document.getElementById('comment_text');
		CommentText.value = 'To '+UserName+': ';
                if (document.getElementById('replyUser') && document.getElementById('replyUser')) {
                    document.getElementById('replyUser').value = document.getElementById('replyUser'+postId).value;
                    document.getElementById('replyUserLogin').value = document.getElementById('replyUserLogin'+postId).value;
                }

		$("#cancel_Reply").show();
                $(".title_comment").hide();
                $("#reply_to_user").html(UserName);
                $(".title_reply_comment").show();


                $('.product_comments_post, .reply').mouseenter(function () {  // disable the display of the links under comments
		$(this).find('.info_product_comments').stop(false, true);
                    }).mouseleave(function () {
		$(this).find('.info_product_comments').stop(false, true);
                    });
                

                $('html, body').animate({scrollTop: $("body").height()}, 800);   

	}

}

function cancelReply() {
	$("#cancel_Reply").hide();
	document.getElementById('comment_text').value='';
	document.getElementById('replyUser').value = '';
	document.getElementById('replyUserLogin').value = '';
        $(".title_comment").show();
        $(".title_reply_comment").hide();
}

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') {
            $('#rows_'+id_product).remove();
        }
    }, "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;
		});
	});
});

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;
}
// hide Alert Message for 3 days
function hideAlertMessage(id_alert){
    $.post("/index.html", {
        action: "action",
        alert_id: id_alert,
        alert: "hide",
        page: "ajax_alert_messages"
    },
    function(data) {
        //alert("Data Loaded: " + data.php_message);
        if (data.php_message == 'hide') {
            $('.alert_massage_container').remove();
        }
    }, "json");
}


function getSubCat(parent_id) {
    $.post('/index.html', {
        action: "action",
        page:'subcats',
        parent_id:parent_id
    },
    function(data) {
        if (data[0].error == 1) {
            alert('Страница не прогрузилась полностю, обновите её пожалуйста!!!');
        } else {
            var options = '';
            for (var i = 0; i < data.length; i++) {
                options += '<option value="' + data[i].optionValue + '">' + data[i].optionDisplay + '</option>';
            }
            $("select#project_category").html(options);
        }
    }, "json");
}
