// Initialize your app
var myApp = new Framework7({
	cacheIgnore:['cart.php','user.php','search.php','user.php?act=index'],
});

// Export selectors engine
var $$ = Dom7;

// Add view
var mainView = myApp.addView('.view-main', {
    // Because we use fixed-through navbar we can enable dynamic navbar
    dynamicNavbar: true
});

var mySlider = myApp.slider('.slider-container', {
	pagination:'.slider-pagination',
	autoplay:3000,
});

myApp.onPageInit('login-screen', function (page) {
	var pageContainer = $$(page.container);
	pageContainer.find('.login-btn').on('click', function () {
		var user_name = pageContainer.find('input[name="user_name"]').val();
		var password = pageContainer.find('input[name="password"]').val();
		var rel_url = pageContainer.find('input[name="rel_url"]').val();

		$$.ajax({ 
			url:'user.php', 
			type:"post",
			dataType:"json",
			data:{"act":"do_login","user_name":user_name,"password":password,"lang_id":language_id,"themes":themes},
			success: function(result){
				if(result.error == 0){
					if(rel_url){
						mainView.router.loadPage(rel_url);
					}else{
						mainView.router.loadPage("user.php?act=index");
					}
				}else{
					myApp.alert(result.message, result.title);
				}
			}
		 });
	});
});  

$$(document).on('pageInit', function (e) {
	var page = e.detail.page;
	if(page.name == 'index'){
		myApp.slider('.slider-container', {
			pagination:'.slider-pagination'
		});
		$$('.home-news').attr('style','margin-bottom:5px;');
	}

	if(page.name == 'list-box'){
		var loading = false;
		var show_type = $$('.list-box').attr('show_type');
		if(show_type == 3){
			var lastIndex = $$('.list-box .row').length*3;
		}else{
			var lastIndex = $$('.list-box .row').length;
		}

		var maxItems = $$('.list-box').attr('total')-1;
		var post_url = $$('.list-box').attr('url');
		var itemsPerLoad = 10;

		$$('.infinite-scroll').on('infinite', function () {
			if (loading) return;
			loading = true;
			setTimeout(function () {
				loading = false;
				if (lastIndex >= maxItems) {
					myApp.detachInfiniteScroll($$('.infinite-scroll'));
					$$('.infinite-scroll-preloader').remove();
					return;
				}
				$$.ajax({ 
					url:post_url, 
					type:"post",
					dataType:"json",
					data:{"is_ajax":1,"start":(lastIndex + 1),"end":(lastIndex + itemsPerLoad),"lang_id":language_id,"themes":themes},
					beforeSend:function(){
					},
					complete:function(){
					},
					success: function(result){
						if(result.error == 0){
							var html = '';
							for (var i = 0; i < result.content.length; i++) {
								value = result.content[i];

								if(result.show_type == 3){
									if(i % 3 == 0){
										html += '<div class="row">';
									}
									html += '<div class="col-33">';
									html += '	<a href="'+value.url+'"><img src="'+value.image+'" width="100%" alt="" ></a> '; 
									html += '	<div class="title"><a href="'+value.url+'">'+value.name+'</a></div>';
									html += '</div>';
									if((i+1) % 3 == 0){
										html += '</div>';	
									}
								}else{
									if(value.image){
										html += '<div class="row"><div class="col-25">';
										html += '	<a href="'+value.url+'"><img src="'+value.image+'" width="100%" alt="" ></a> '; 
										html += '</div>';
										html += '<div class="col-75">';
										html += '	<div class="title"><a href="'+value.url+'">'+value.name+'</a></div>';
										html += '	<div class="content">'+value.description;
										html += '		<div class="date">'+value.date_added+'</div>';
										html += '	</div>';
										html += '</div></div>';

									}else{
										html += '<div class="row"><div class="col-100">';
										html += '		<div class="title"><a href="'+value.url+'">'+value.name+'</a></div>';
										html += '		<div class="content">';
										html += '			<div class="date">'+value.date_added+'</div>';
										html += '		</div>';
										html += '	</div></div>';
									}
								}
								
							}

							$$('.list-box').append(html);

							if(show_type == 3){
								lastIndex = $$('.list-box .row').length*3;
							}else{
								lastIndex = $$('.list-box .row').length;
							}
						}
					}
				 });
			}, 1000);
		});         
	}

	if(page.name == 'product-list'){
		var loading = false;
		var lastIndex = $$('.list-box .row').length;
		var maxItems = $$('.list-box').attr('total')-1;
		var post_url = $$('.list-box').attr('url');
		var itemsPerLoad = 10;

		$$('.infinite-scroll').on('infinite', function () {
			if (loading) return;
			loading = true;
			setTimeout(function () {
				loading = false;
				if (lastIndex >= maxItems) {
					myApp.detachInfiniteScroll($$('.infinite-scroll'));
					$$('.infinite-scroll-preloader').remove();
					return;
				}
				$$.ajax({ 
					url:post_url, 
					type:"post",
					dataType:"json",
					data:{"is_ajax":1,"start":(lastIndex + 1),"end":(lastIndex + itemsPerLoad),"lang_id":language_id,"themes":themes},
					beforeSend:function(){
					},
					complete:function(){
					},
					success: function(result){
						if(result.error == 0){
							for (var i = 0; i < result.content.length; i++) {
								value = result.content[i];
								var html = '';
								html += '<div class="row">'; 
								html += '	<div class="col-25">'; 
								html += '		<a href="'+value.url+'"><img src="'+value.image+'" width="100%" alt="" ></a> ';  
								html += '	</div>'; 
								html += '	<div class="col-75">'; 
								html += '		<div class="product-title"><a href="'+value.url+'">'+value.name+'</a></div>'; 
								html += '		<div class="product-desc">'+value.description+'</div>'; 
								html += '		<div class="product-box">'; 
								html += '			<div class="product-price">'+value.shop_price+'</div>'; 
								html += '			<div class="add-cart"><a href=""><img src="/'+skin+'/images/button_cart.png" width="100%" /></a></div>';
								html += '		</div>'; 
								html += '		<div style="clear:both;"></div>'; 
								html += '	</div>'; 
								html += '	<div style="clear:both;"></div>';          
								html += '</div>';

								$$('.list-box').append(html);
								lastIndex = $$('.list-box .row').length;
							}
						}
					}
				 });
			}, 1000);
		});         
	}

	if(page.name == 'register'){
		$$('#mobile-submit').on('click', function () {
			var mobile = $$('input[name="mobile"]').val();
			var password = $$('input[name="password1"]').val();
			var confirm_password = $$('input[name="confirm_password1"]').val();

			$$.ajax({ 
				url:'user.php', 
				type:"post",
				dataType:"json",
				data:{"act":"do_register","mobile":mobile,"password":password,'confirm_password':confirm_password,"lang_id":language_id,"themes":themes},
				success: function(result){
					if(result.error == 0){
						mainView.router.loadPage("user.php?act=index");
					}else{
						myApp.alert(result.message, result.title);
					}
				}
			 });			
		});

		$$('#email-submit').on('click', function () {
			var email = $$('input[name="email"]').val();
			var password = $$('input[name="password2"]').val();
			var confirm_password = $$('input[name="confirm_password2"]').val();

			$$.ajax({ 
				url:'user.php', 
				type:"post",
				dataType:"json",
				data:{"act":"do_register","email":email,"password":password,'confirm_password':confirm_password,"lang_id":language_id,"themes":themes},
				success: function(result){
					if(result.error == 0){
						myApp.alert(result.message, result.title);
					}else{
						myApp.alert(result.message, result.title);
					}
				}
			 });			
		});
	}

	if(page.name == 'product-detail'){
		myApp.slider('.product-image .slider-container', {
			pagination:'.slider-pagination',
			autoplay:3000,
		});

		$$('.amount-action-min').on('click', function () {
			var quantity = parseInt($$('#quantity').val());
			$$('#quantity').val(quantity-1);
			if(parseInt($$('#quantity').val()) == 1){
				$$('.amount-action-min').addClass('disabled');
			}
		});

		$$('.amount-action-max').on('click', function () {
			var quantity = parseInt($$('#quantity').val());
			$$('.amount-action-min').removeClass('disabled');
			$$('#quantity').val(quantity+1);
		});

		$$('#quantity').on('blur', function () {
			var quantity = parseInt($$('#quantity').val());
			if(quantity == 1){
				$$('.amount-action-min').addClass('disabled');
			}else{
				$$('.amount-action-min').removeClass('disabled');
			}
		});

		$$('.add-cart').on('click', function () {
			var quantity = parseInt($$('#quantity').val());
			var product_id = parseInt($$('#product_id').val());
			var lang_id = $$('input[name="lang_id"]').val();
			add_to_cart(product_id,quantity,lang_id);
		});
	}

	if(page.name == 'info-detail'){
		$$('.info-share').on('click', function () {
			$$.ajax({ 
				url:'information.php', 
				type:"post",
				dataType:"json",
				data:{"act":"share","id":$$('#information_id').val(),"lang_id":language_id,"themes":themes},
				success: function(result){
					if(result.error == 0){
						$$('#share-num').html(result.content);
					}else{
						myApp.alert(result.message, result.title);
					}
				}
			 });
		});
	}

	if(page.name == 'get-password'){
		$$('.password-btn').on('click', function () {
			$$.ajax({ 
				url:'user.php', 
				type:"post",
				dataType:"json",
				data:{"act":"get_password","mobile_email":$$('#mobile_email').val(),"lang_id":language_id,"themes":themes},
				success: function(result){
					if(result.error == 0){
						myApp.alert(result.message, result.title);
					}else{
						myApp.alert(result.message, result.title);
					}
				}
			 });
		});
	}

	if(page.name == 'user-info'){
		$$('.button-submit').on('click', function () {
			var name = $$('input[name="name"]').val();
			var email = $$('input[name="email"]').val();
			var telephone = $$('input[name="telephone"]').val();
			var mobile = $$('input[name="mobile"]').val();
			var fax = $$('input[name="fax"]').val();
			var password = $$('input[name="password"]').val();

			$$.ajax({ 
				url:'user.php', 
				type:"post",
				dataType:"json",
				data:{"act":"info","name":name,"email":email,"telephone":telephone,"mobile":mobile,"fax":fax,"password":password,"lang_id":language_id,"themes":themes},
				success: function(result){
					if(result.error == 0){
						myApp.alert(result.message, result.title);
					}else{
						myApp.alert(result.message, result.title);
					}
				}
			 });
		});
	}

	if(page.name == 'address-list'){
		$$('.confirm-ok').on('click', function () {
			var address_id = $$(this).attr('ref');
			myApp.confirm(alert_delete_address, prompt, function () {
				$$.ajax({ 
					url:'user.php', 
					type:"get",
					dataType:"json",
					data:{"act":"del_address","id":address_id,"lang_id":language_id,"themes":themes},
					success: function(result){
						if(result.error == 0){
							$$('.address_'+address_id).remove();
						}else{
							myApp.alert(result.message, result.title);
						}
					}
				 });				
			});
		});
	}

	if(page.name == 'address-info'){
		$$("#province").change(function(){
			var province = $$(this).val();
			if(province == 0){
				return ;
			}
			$$.ajax({ 
				url:'user.php', 
				type:"post",
				dataType:"json",
				data:{"act":"get_region","id":province,"lang_id":language_id,"themes":themes},
				success: function(result){
					if(result.error == 0){
						$$('#city').html("<option value=\"0\">请选择城市</option>"+result.content);
						$$('#district').html("<option value=\"0\">请选择地区</option>");
					}
				}
			 });
		});	
		
		$$("#city").change(function(){
			var city = $$(this).val();
			if(city == 0){
				return ;
			}
			$$.ajax({ 
				url:'user.php', 
				type:"post",
				dataType:"json",
				data:{"act":"get_region","id":city,"lang_id":language_id,"themes":themes},
				success: function(result){
					if(result.error == 0){
						$$('#district').html("<option value=\"0\">请选择地区</option>"+result.content);
					}
				}
			 });			
		});	

		$$('.button-submit').on('click', function () {
			var province = $$('#province').val();
			var city = $$('#city').val();
			var district = $$('#district').val();
			var address = $$('#address').val();
			var name = $$('input[name="name"]').val();
			var mobile = $$('input[name="mobile"]').val();
			var address_id = $$('input[name="address_id"]').val();
			var act='add_address';
			if(address_id){
				act='edit_address';
			}
			$$.ajax({ 
				url:'user.php', 
				type:"post",
				dataType:"json",
				data:{"act":act,"name":name,"mobile":mobile,"address":address,"id":address_id,"district":district,"city":city,"province":province,"lang_id":language_id,"themes":themes},
				success: function(result){
					if(result.error == 0){
						myApp.alert(result.message, result.title);
						mainView.router.loadPage("user.php?act=address");
					}else{
						myApp.alert(result.message, result.title);
					}
				}
			 });
		});	

	}

	if(page.name == 'order-info'){
		$$('.button-cancel').on('click', function () {
			myApp.confirm(alert_cancel_order, function () {
				var order_id = $$('input[name="order_id"]').val();
				var lang_id = $$('input[name="lang_id"]').val();
				$$.ajax({ 
					url:'user.php', 
					type:"post",
					dataType:"json",
					data:{"act":'order_cancel',"id":order_id,"lang_id":language_id,"themes":themes},
					success: function(result){
						if(result.error == 0){
							myApp.alert(result.message, result.title);
							mainView.router.loadPage("user.php?act=order_detail&id="+order_id+"&lang_id="+lang_id);
						}else{
							myApp.alert(result.message, result.title);
						}
					}
				 });
			});
		});	
	
		$$('.button-payment').on('click', function () {
			var order_id = $$('input[name="order_id"]').val();
			$$.ajax({ 
				url:'user.php', 
				type:"post",
				dataType:"json",
				data:{"act":'order_payment',"id":order_id,"lang_id":language_id,"themes":themes},
				success: function(result){
					if(result.error == 0){
						if(result.content){
							document.write( result.content );
						}else{
							myApp.alert(result.message, result.title);
						}
					}else{
						myApp.alert(result.message, result.title);
					}
				}
			 });
		});	
		
		$$('.button-receiving').on('click', function () {
			myApp.confirm(alert_receiving, function () {
				var order_id = $$('input[name="order_id"]').val();
				var lang_id = $$('input[name="lang_id"]').val();
				$$.ajax({ 
					url:'user.php', 
					type:"post",
					dataType:"json",
					data:{"act":'order_receiving',"id":order_id,"lang_id":language_id,"themes":themes},
					success: function(result){
						if(result.error == 0){
							myApp.alert(result.message, result.title);
							mainView.router.loadPage("user.php?act=order_detail&id="+order_id+"&lang_id="+lang_id);
						}else{
							myApp.alert(result.message, result.title);
						}
					}
				 });
			 });
		});	
	
		$$('.button-return').on('click', function () {
			myApp.confirm(alert_refund_returns , function () {
				var order_id = $$('input[name="order_id"]').val();
				var lang_id = $$('input[name="lang_id"]').val();

				$$.ajax({ 
					url:'user.php', 
					type:"post",
					dataType:"json",
					data:{"act":'order_return',"id":order_id,"lang_id":language_id,"themes":themes},
					success: function(result){
						if(result.error == 0){
							myApp.alert(result.message, result.title);
							mainView.router.loadPage("user.php?act=order_detail&id="+order_id+"&lang_id="+lang_id);
						}else{
							myApp.alert(result.message, result.title);
						}
					}
				 });
			 });
		});	
	}

	if(page.name == 'cart'){
		cart_event();
	}

	$$('.form-inquiry-json').on('click', function(){
		var subject = $$('input[name="subject"]').val();
		var content = $$('textarea[name="content"]').val();
		var name = $$('input[name="name"]').val();
		var tel = $$('input[name="tel"]').val();
		var email = $$('input[name="email"]').val();
		var code = $$('input[name="code"]').val();

		$$.ajax({ 
			url:'inquiry.php', 
			type:"post",
			dataType:"json",
			data:{"act":'submit',"subject":subject,"content":content,"name":name,"tel":tel,"email":email,"code":code},
			success: function(result){
				if(result.error == 0){
					myApp.alert(result.message, result.title);
					mainView.router.load({
						url:"index.php?lang_id="+language_id,
						ignoreCache:true,
						animatePages:false,
						reload:true,
					});
				}else{
					myApp.alert(result.message, result.title);
				}
			}
		 });
	});

})   

function cart_event(){
	$$('.amount-action-max').on('click', function () {
		var quantity = parseInt($$(this).parent('.amount-confirm-box').find('input[name="quantity"]').val());
		$$(this).parent('.amount-confirm-box').find('.amount-action-min').removeClass('disabled');
		$$(this).parent('.amount-confirm-box').find('input[name="quantity"]').val(quantity+1);
		var product_id = $$(this).parent('div').find('input[name="product_id"]').val();
		update_cart('update',product_id,quantity+1);
	});

	$$('.amount-action-min').on('click', function () {
		var quantity = parseInt($$(this).parent('.amount-confirm-box').find('input[name="quantity"]').val());
		$$(this).parent('.amount-confirm-box').find('input[name="quantity"]').val(quantity-1);
		if(parseInt($$(this).parent('.amount-confirm-box').find('input[name="quantity"]').val()) == 1){
			$$(this).addClass('disabled');
		}
		var product_id = $$(this).parent('div').find('input[name="product_id"]').val();
		update_cart('update',product_id,quantity-1);
	});

	$$('.amount-text').on('blur', function () {
		var quantity = parseInt($$(this).val());
		if(quantity == 1){
			$$(this).parent('.amount-confirm-box').find('.amount-action-min').addClass('disabled');
		}else{
			$$(this).parent('.amount-confirm-box').find('.amount-action-min').removeClass('disabled');
		}
		var product_id = $$(this).parent('div').find('input[name="product_id"]').val();
		update_cart('update',product_id,quantity);
	});

	$$('.cart-del').on('click', function () {
		var product_id = $$(this).parent('div').parent('div').parent('.product-info').find('input[name="product_id"]').val();
		update_cart('delete',product_id,0);
	});

	$$('.submit-cart').on('click', function () {
		var payment = $$('input[name="payment"]:checked').val();
		var address = $$('input[name="address"]:checked').val();

		$$.ajax({ 
			url:'cart.php', 
			type:"post",
			dataType:"json",
			data:{"act":'submit',"payment":payment,"address":address,"lang_id":language_id,"themes":themes},
			success: function(result){
				if(result.error == 0){
					if(result.content){
						document.write( result.content );
					}else{
						myApp.alert(result.message, result.title);
					}
				}else{
					myApp.alert(result.message, result.title);
				}
			}
		 });
	});

}

function update_cart(act,product_id,quantity){
	$$.ajax({ 
		url:'cart.php', 
		type:"get",
		dataType:"json",
		async:false, 
		data:{"act":act,"id":product_id,"quantity":quantity,"lang_id":language_id,"themes":themes},
		success: function(result){
			if(result.error == 0){
				mainView.router.load({
					url:'cart.php?act=index',
					ignoreCache:true,
					animatePages:false,
					reload:true,
				});
			}else{
				myApp.alert(result.message,result.title);
			}
		}
	 });
}

function add_to_cart(id,quantity,lang_id){	
	if(id == 0){
		return ;
	}
	$$.ajax({ 
		url:'cart.php', 
		type:"post",
		dataType:"json",
		data:{"act":"add","id":id,"quantity":quantity,"lang_id":language_id,"themes":themes},
		success: function(result){
			if(result.error == 0){
				mainView.router.load({
					url:"cart.php?act=index&lang_id="+language_id,
					ignoreCache:true,
					animatePages:false,
					reload:true,
				});
			}else if(result.error == 2){
				var rel_url = 'product.php?act=detail&id='+id+"&lang_id="+language_id;
				mainView.router.loadPage("user.php?act=login&lang_id="+language_id+'&rel_url='+encodeURIComponent(rel_url));
			}else{
				myApp.alert(result.message, result.title);
			}
		}
	 });
}

function MathRand(){
	var num="";
	for(var i=0;i<6;i++)	{
		num+=Math.floor(Math.random()*10);
	}
	return num;
} 

function submit_search(obj){
	var keywords = $$(obj).parent('div').parent('div').find('input[name="keywords"]').val();
	mainView.router.loadPage('search.php?keywords='+keywords);
}

$$("#sel_lang").change(function(){
	var lang_id = $$(this).val();
	window.location.href = 'index.php?lang_id='+lang_id;
});
