$.fn.getIndex = function(){
	var $p=$(this).parent().children();
	return $p.index(this);
};
(function($){ 
	$.fn.wrapChildren = function(options) {
		var options = $.extend({
			childElem : undefined,
			sets : 1,
			wrapper : 'div'
		}, options || {});
		if (options.childElem === undefined) return this;
		return this.each(function() {
			var elems = $(this).children(options.childElem);
			var arr = [];

			elems.each(function(i,value) {
				arr.push(value);
				if (((i + 1) % options.sets === 0) || (i === elems.length -1))
					{
					var set = $(arr);
					arr = [];
					set.wrapAll($("<" + options.wrapper + ">"));
				}
			});
		});

	}

})(jQuery);

(function($){ 
	$.fn.resizeImg = function(new_width,new_height) {
		this.each(function(){
			var oldwidth = this.width;                   
			var oldheight = this.height;
			if (oldwidth>oldheight) this.height=new_height;
			if (oldheight>oldwidth) this.width=new_width;
			if(oldheight==oldwidth)                    
				{                                
				this.width=new_width;
				this.height=new_height;                          
			}  
			return this;

		});
	};          
})(jQuery);


$.easing.elasout = function(x, t, b, c, d) {
	var s=1.70158;var p=0;var a=c;
	if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
	if (a < Math.abs(c)) { a=c; var s=p/4; }
	else var s = p/(2*Math.PI) * Math.asin (c/a);
	return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
};
function clean(str)
{
	str = str.replace(/^[ ]+|[ ]+$/g, '');

	str = str.replace(/^[\r\n]+|[\r\n]+$/g, '');

	str = str.replace(/^[ ]+|[ ]+$/g, '');

	str = str.replace(/(\s\s+)/g, " ");

	str = str.replace(" ","_");

	return str;
}

function ajax_upload(button_id,input_name,config_ws,button_response)
{
	var button = $('#'+button_id), interval; 
	new AjaxUpload(button,{
		name: 'myfile',
		data : {input_name : input_name },
		action: config_ws+'/upload.php',
		onSubmit : function(file , ext){
			button.text('Uploading'); 
			if (! (ext && /^(jpg|png|jpeg|gif|bmp)$/.test(ext))){
				// extension is not allowed
				alert('Error: invalid file extension');
				// cancel upload
				return false;
			}
			this.disable(); 
			interval = window.setInterval(function(){
				var text = button.text();
				if (text.length < 13){
					button.text(text + '.');
				} else {
					button.text('Uploading');
				}
			}, 200); 
		},
		onComplete: function(file, response){
			button.text('Upload Again');
			window.clearInterval(interval);
			// enable upload button
			this.enable();
			// add file to the list
			$('span#'+button_response).html(response);
		} 
	});  
}


function randomstring()
{
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}


function findParentNode(parentName, childObj) {
	var testObj = childObj.parentNode;   
	while(testObj.className != parentName) {        
		testObj = testObj.parentNode;
	}
	return testObj;
}
function ismaxlength(obj)
{
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "";
	if (obj.getAttribute && obj.value.length>mlength)
		obj.value=obj.value.substring(0,mlength);
}

function tiny_init_simple()
{
	tinyMCE.init({
		mode : "textareas",
		theme : "simple"
	});
}
function tiny_init_post()
{
	tinyMCE.init({
		mode : "textareas",
		theme : "advanced",        
		plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,rj_insertcode",

		// Theme options

		entities : "",
		forced_root_block : false,
		paste_use_dialog : false,
		paste_auto_cleanup_on_paste : true,
		paste_convert_middot_lists : true,
		paste_unindented_list_class : "unindentedList",
		paste_convert_headers_to_strong : true,
		paste_insert_word_content_callback : "convertWord",
		// Theme options
		theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,styleselect,formatselect",
		theme_advanced_buttons3 : "outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
		theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,insertfile,insertimage,rj_insertcode",    

		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,  
		width : "600",  
		height: "400",       
		font_size_style_values : "medium",
		relative_urls : false,
		remove_script_host : false
	});

}
function Set_Cookie(cookieName,cookieValue,nDays)
{

	var today = new Date();

	var expire = new Date();

	if (nDays==null || nDays==0) nDays=1;

	expire.setTime(today.getTime() + 3600000*24*nDays);

	document.cookie = cookieName+"="+escape(cookieValue)

	+ ";expires="+expire.toGMTString();

}
function Get_Cookie( name ) 
{

	var start = document.cookie.indexOf( name + "=" );

	var len = start + name.length + 1;

	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )

		{

		return null;

	}



	if ( start == -1 ) return null;

	var end = document.cookie.indexOf( ";", len );

	if ( end == -1 ) end = document.cookie.length;

	return unescape( document.cookie.substring( len, end ) );

}

//css funtion

function changeBg() {
	document.getElementById('ovan').style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true', src='image.png', sizingMethod='scale')";
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	if (restore) selObj.selectedIndex=0;
}
function fn_reload_captcha(path){    
	$('#reload_button').attr({src : path+"/images/indicator_arrows.gif"});
	$("#captcha_img").attr({ src : 'captcha.php' + '?' + (new Date()).getTime() });        
	setTimeout(function(){$('#reload_button').attr({src : path+"/images/indicator_arrows_static.gif"}); }, 500);
}
function register_submit()
{
	var str = $("#register").serialize();

	$("#error").show().html('Đang xử lí..');

	$.getJSON('ajax.php',str,function(res){
		if (res.status=='1000')      
			$('#error').show().html('<div class="b_tbl">Báo lỗi :<br />'+res.data+'</div>'); 
		else 
			{
			//alert(res.data);			
			window.location=res.data;

		}


	});

	return false;	
}

function download_free(gameid,id)
{
	$.post('gameajax.php', { gameid : gameid, id : id , inpage : 'download'},function(data){		
		if (data) alert('Error :'+data);		
		else
			{
			alert("Thông tin tải game sẽ được gửi đến máy điện thoại của bạn dưới dạng tin nhắn trong ít phút");			
			location.href='http://mclub.vn';
		}

	})
	return false;
}

function login_submit()
{
	var str = $("#login").serialize();

	$("#error").show().html('Đang xử lí..');

	$.getJSON('ajax.php',str,function(res){
		if (res.status=='1000')      
			$('#error').show().html('<div class="left">&nbsp;</div><div class="right"><span>'+res.data+'</span></div> '); 
		else window.location=res.data;
	});
	return false;
}
function check_phone()
{
	var brand = $("input#sbrand").val();

	var model = $('input#smodel').val();

	if (!brand || !model) alert("Hãy nhập vào dòng máy và đời máy của bạn");

	else
		{
		var gamenum = $('input#gamenum').val();
		
		$("#result").show().html('Đang xử lí..');
		$.post('gameajax.php', { brand : brand, model : model , gamenum : gamenum , inpage : 'check_sphone' } ,function(data){
			$('#result').show().html(data);       
		});

	}
	return false;
}
function jump(value)
{
	$.scrollTo( '#'+value, 500, { easing:'elasout' });
	return false;
}
function add_to(gameid,type)
{
	$.post('gameajax.php',{ id : gameid , type : type , inpage : 'add_to' },function(data){

		if (data) call_login('add_to',gameid,type); 
		else 
			{
			var current = $('span#incart').html();

			current = parseInt(current)+1;

			$('span#incart').html(current);

			alert('Bạn đã add thành công');
		}


	});

	return false;
}
function call_login(page,gameid,type)
{
	$("#thickpage").val(page);
	$('#thickvar1').val(gameid);
	$("#thickvar2").val(type);
	tb_show('','#TB_inline?height=430&amp;width=560&amp;inlineId=thickload&amp;modal=false',true);
	return false;
}
function dangnhap_popup()
{
	var data = $('#thickform').serialize();	
	$.post('ajax.php', data , function(res){
		if (res) $("#pop_error").show().html(res);
		else
			{
			tb_remove();
			alert('Bạn đã add thành công');
			location.reload();
		}
	});
	return false;

}
function changepass()
{
	var str = $("#changepass").serialize();

	$("#perror").show().html('Đang xử lí..');

	$.post('ajax.php', str , function(res){

		if (res) $("#perror").html(res);

		else {
			$("#perror").html('').hide();

			alert('Bạn đã đổi pass thành công!');

			location.reload();
		}

	});
	return false;
}
function changeinfo()
{
	var str = $("#changeinfo").serialize();

	$("#ierror").show().html('Đang xử lí..');

	$.post('ajax.php', str , function(res){

		if (res) $("#ierror").html(res);

		else {
			$("#ierror").html('').hide();

			alert('Bạn đã cập nhật thông tin thành công!');

			location.reload();
		}
	});
	return false;
}
function calculator()
{
	var total_all=0;

	$('div.list_sp').each(function(){

		price = $(this).find("span.price").attr('title');

		price = parseInt(price);

		quality = $(this).find("input.quality").val();

		quality = parseInt(quality);

		total = price*quality;

		$(this).find("span.total").html(total);

		total_all += parseInt(total);

	})

	$('span#total_all').html(total_all);
	return false;
}
function rm_user_cart_list(id)
{
	var ok =confirm("Bạn có muốn xóa sản phẩm này khỏi giỏ hàng của bạn?");	
	if (ok)
		{
		$.post('gameajax.php',{ id : id , inpage : "cart_remove" },function(res){
			if (res) alert(res);
			else 
				{
				$("div#list_sp"+id).remove();
				calculator();

				var current = $('span#incart').html();

				current = parseInt(current)-1;

				$('span#incart').html(current);


			}
		});

	}
	return false;
}
function purchase()
{


	var items='';
	var i=1;
	$('div.list_sp').each(function(){
		id = $(this).find("a.gameid").attr("title");					
		id = parseInt($.trim(id));					
		price = $(this).find("span.price").attr('title');					
		price = parseInt($.trim(price));					
		quality = $(this).find("input.quality").val();					
		quality = parseInt($.trim(quality));					
		total = price*quality;					
		$(this).find("span.total").html(total);
		items +=i+"_id="+id+"&"+i+"_price="+price+"&"+i+"_quality="+quality+"&"+i+"_total="+total+"&";					
		i++;
	})	

	str = items+'inpage=purchase';	
	$.get ('gameajax.php',str ,function(res){
		if (res) alert(res); 
		else
			{
			alert("Cảm ơn bạn đã thanh toán");

			location.href='/game-da-mua.html';
		}
	});
	return false;

}
function rm_user_favour_list(gameid)
{
	var ok =confirm("Bạn có muốn xóa sản phẩm này khỏi list game yêu thích của bạn không?");    
	if (ok)
		{
		$.post('gameajax.php',{ gameid : gameid , inpage : "favour_remove" },function(res){
			if (res) alert(res);
			else 
				$("div#list_favour"+gameid).remove();
		});

	}
	return false;
}
