﻿// iSolus framework.
var iSolus = new function(){

	// add page hanlder
	this.AddPage = function(){
		$.fn.colorbox({
			width:			'400px',
			height:			'400px',
			inline:			true,									
			href:			'#add-page-panel',		
			title:			'THÊM TRANG MỚI',				
			scrolling:		true,
			transition:		'none',
			overlayClose:	false
		});
	}
	
	// add page validator
	this.AddPageSubmition = function(){
		if($(".lbvalPagename").val().length <= 0){
			alert('Vui lòng nhập tên hiển thị của trang mới.');
			return false;
		}
		// make ajax call submit.
		var datapram = { ac: 'addPages', title: $(".lbvalPagename").val(), order: $(".txOrder").val(), parent: $(".lsParentTab").val() }
		// request authentication user.
		$.ajax({
			type: "POST",
			url: "widgetServices.aspx",
			data: datapram,
			dataType: "json",
			success: function(rVal) {
				var Json = eval(rVal);
				if(Json.status == '0'){
					$.jGrowl("Thêm trang mới thành công. hệ thống sẽ tự động làm tươi sau vài giây nữa.");
					window.location.href = "?tab="+ Json.msg;
				}else{
					$.jGrowl("Thêm trang mới thất bại, vui lòng kiểm tra lại các thống số nhập vào.");
				}
			},
			error: function(){
				$.jGrowl("Không thể gửi thông tin yêu cầu lên máy chủ, vui lòng thử lại sau ít phút nữa.");
			}
		});
	}
	
	// add widget handler
	this.AddWidget = function(){
		$.fn.colorbox({
			width:			'50%',
			height:			'60%',						
			inline:			true,
			href:			'#add-widget-panel',			
			title:			'THÊM ĐỐI TƯỢNG VÀO TRANG',				
			scrolling:		true,
			transition:		'none',
			overlayClose:	false
		});
	}
	
	// add widget validator
	this.AddWidgetSubmition = function(){
		// add widget validator.
		if($(".lsWidgets").val().length <= 0){
			alert('Vui lòng chọn đối tượng cần thêm vào trang hiện thời.');
			return false;
		}
		if($(".lsWidgetPosition").val().length <= 0){
			alert('Vui lòng chọn vị trí hiển thị của đối tượng trên trang.');
			return false;
		}
		if($(".lsWidgetDisplay").val().length <= 0){
			alert('Vui lòng chọn chế độ hiển thị của đối tượng trên trang.');
			return false;
		}	
		// make ajax call submit.
		var datapram = { ac: 'addWidgets', widget: $(".lsWidgets").val(), tmptitle: $(".lsWidgets option:selected").text(), title: $(".txWidgetTitle").val(), pos: $(".lsWidgetPosition").val(), Order: $(".txWidgetOrder").val(), diplay: $(".lsWidgetDisplay").val() }
		// request authentication user.
		$.ajax({
			type: "POST",
			url: "widgetServices.aspx",
			data: datapram,
			dataType: "json",
			success: function(rVal) {
				var Json = eval(rVal);
				if(Json.status == '0'){
					$.jGrowl("Thêm widget vào trang thành công. hệ thống sẽ tự động làm tươi sau vài giây nữa.");
					window.location.href = "/";
				}else{
					$.jGrowl("Thêm widget vào thất bại, vui lòng kiểm tra lại các thống số nhập vào.");
				}
			},
			error: function(){
				$.jGrowl("Không thể gửi thông tin yêu cầu lên máy chủ, vui lòng thử lại sau ít phút nữa.");
			}
		});	
	}   
	
	// quickly post contents.
	this.postContents = function(){
		$.fn.colorbox({
			width:			'80%',
			height:			'80%',						
			resize:			false,				
			iframe:			true,
			title:			'ĐĂNG NỘI DUNG NHANH',				
			href:			'/widgetServices.aspx?ac=cmsquickeditor',
			scrolling:		true,
			transition:		'none',
			overlayClose:	false
		});
		return false;
	}
		
	// login handler function
	this.doLogin = function(){
		// validate login info.
		if( $("#username").val() == ""){
			alert("Vui lòng nhập tên truy cập chính xác. \n Lưu ý: Tên truy cập phân biệt chữ hoa và chữ thường."); 
			$("#username").focus();
			return false;
		}
		if( $("#password").val() == ""){					
			alert("Vui lòng nhập mật mã truy cập chính xác. \n Lưu ý: Mật mã truy cập phân biệt chữ hoa và chữ thường.");
			$("#password").focus();
			return false;
		}
		// make ajax call submit.
		var datapram = { ac: 'requestauthorized', u: $("#username").val(), p: $("#password").val(), r: $("#remember").val() }
		// request authentication user.
		$.ajax({
			type: "POST",
			url: "widgetServices.aspx",
			data: datapram,
			dataType: "json",
			success: function(rVal) {
				var Json = eval(rVal);
				switch (Json.status) {
					case '0':  // successfull.
						// refresh window base.
						window.location.href = Json.msg;
						break;
					case '-1': // wrong username
						alert("Đăng nhập thất bại, sai tên truy cập hoặc tên truy cập không tồn tại.");
						$("#username").val('');
						$("#username").focus();
						break;
					case '-2': // wrong password
						alert("Đăng nhập thất bại, sai mật mã truy cập.");
						$("#password").val('');
						$("#password").focus();
						break;					
				}
			},
			error: function() {
				alert("Không thể gửi thông tin yêu cầu chứng thực người dùng, vui lòng thử lại sau ít phút nữa.");
				$("#username").val('');
				$("#password").val('');							
			}
		});

		// prevent default event click.
		return false;
	}
	
	// widget update handler
	this.widgetUpdate = function(obj){
		var widgetInstanceId = $(obj).closest('div.widget').attr('id');
		// display dialog edit.
		$.fn.colorbox({
			width:			'850px',
			height:			'650px',						
			resize:			true,				
			iframe:			true,
			title:			'CẬP NHẬT THÔNG TIN',				
			href:			'/widgetServices.aspx?ac=loadEditCtr&widgetInstanceId='+ widgetInstanceId,
			scrolling:		true,
			transition:		'none',
			overlayClose:	false
		});
		return false;	
	}
	
	// widget settings handler.
	this.widgetSettings = function(obj){
		var widgetInstanceId = $(obj).closest('div.widget').attr('id');
		// display dialog edit.
		$.fn.colorbox({
			width:			'400px',
			height:			'50%',						
			resize:			true,				
			iframe:			true,
			title:			'CẤU HÌNH WIDGETS',				
			href:			'/widgetServices.aspx?ac=wi-settings&widgetInstanceId='+ widgetInstanceId,
			scrolling:		true,
			transition:		'none',
			overlayClose:	false
		});
		return false;
	}
	
	// widget delete handler
	this.widgetDelete = function(obj){
		// get widget title.
		var widgetTitle = $(obj).closest('div.tl').find('span.wdtitle').html();
		var widgetInstanceId = $(obj).closest('div.widget').attr('id');
		if(confirm('Xóa đối tượng ['+ widgetTitle +'] ra khỏi trang hiện thời? nhấn [OK] nếu đồng ý, [CANCEL] để hủy bỏ.')){
			$.ajax({
				type: "POST",
				url: "/widgetServices.aspx?ac=delete&widgetInstanceId="+ widgetInstanceId,
				data: "{}",						
				dataType: "json",
				success: function(rVal){
					var rJson = eval(rVal);
					if(rJson.status == '0'){
						window.location.href = rJson.msg;	
					}else{
						$.jGrowl("<span class='error'>"+ rJson.msg +"</span>", 
							{ 
								header: '<h1>' + rJson.header +'</h1><p>&nbsp;</p>', 
								life: 6000 
							}
						);
					}
				}
			});			
		}		
		return false;	
	}
	
	// widget move handler
	this.moveWidget = function(obj, panel){		
		var widgetInstanceId = $(obj).closest('div.widget').attr('id');
		$.ajax({
			type: "POST",
			url: "/widgetServices.aspx?ac=move&widgetInstanceId="+ widgetInstanceId +"&newPosition="+ panel,
			data: "{}",						
			dataType: "json",
			success: function(rVal){
				var rJson = eval(rVal);					
				if(rJson.status == '0'){
					window.location.href = rJson.msg;	
				}else{
					$.jGrowl("<span class='error'>"+ rJson.msg +"</span>", 
						{ 
							header: '<h1>' + rJson.header +'</h1><p>&nbsp;</p>', 
							life: 6000 
						}
					);
				}
			}
		});
		return false;
	}
	
	// widget order handler
	this.orderWidget = function(obj, order){
		var widgetInstanceId = $(obj).closest('div.widget').attr('id');
		$.ajax({
			type: "POST",
			url: "/widgetServices.aspx?ac=order&widgetInstanceId="+ widgetInstanceId +"&orderUp="+ order,
			data: "{}",
			dataType: "json",
			success: function(rVal){
				var rJson = eval(rVal);	
				if(rJson.status == '0'){
					window.location.href = rJson.msg;	
				}else{
					$.jGrowl("<span class='error'>"+ rJson.msg +"</span>", 
						{ 
							header: '<h1>' + rJson.header +'</h1><p>&nbsp;</p>', 
							life: 6000 
						}
					);
				}
			}
		});
		return false;
	}

	// insert and update cookies.
	this.InsertUpdateCookie = function(cookieName, oKey, oVal){
		var oArr = new Array();
		if ($.cookies.get(cookieName) != null)
		{
			// insert and update the cookie values.
			var data = $.cookies.get(cookieName);
			var isExists = false;

			for (var i = 0; i < data.length; i++)
			{
				if (data[i].key == oKey)
				{
					isExists = true; // update
					oArr[i] = { key: oKey, value: oVal };
				}
				else
				{
					// update the old items
					oArr[i] = { key: data[i].key, value: data[i].value };
				}
			}

			// if not exist then insert the new ones to the array
			if (isExists == false)
			{
				oArr.push({ key: oKey, value: oVal });
			}

		} else
		{
			oArr.push({ key: oKey, value: oVal });
		}

		// insert new item to cookie.    
		$.cookies.set(cookieName, oArr);
	}

	// get cookie value
	this.GetCookieValue = function(cookieName, oKey){
		var rVal = "";

		if ($.cookies.get(cookieName) != null)
		{
			var data = $.cookies.get(cookieName);
			for (var i = 0; i < data.length; i++)
			{
				if (data[i].key == oKey)
					rVal = data[i].value;
			}
		}

		return rVal;
	}

	// delete cookies.
	this.DeleteCookie = function(cookieName){
		$.cookies.set(cookieName, null);
	}  	
	
	// handler messages.
	this.handlerMessages = function(MessageCode){
		if(MessageCode != ''){
			switch(MessageCode){
				case 'awsuccess':
					$.jGrowl("<span class='success'>Thêm đối tượng vào trang web thành công.</span>", 
						{ 
							header: '<h1>Thông báo!</h1><p>&nbsp;</p>', 
							life: 6000 
						}
					);
					break;
				case 'awerror':
					$.jGrowl("<span class='error'>Không đưa đối tượng vào trang hiện thời được.</span>", 
						{ 
							header: '<h1>Thông báo!</h1><p>&nbsp;</p>', 
							life: 6000 
						}
					);
					break;
				case 'uwssuccess':
					$.jGrowl("<span class='success'>Cập nhật cấu hình đối tượng thành công.</span>", 
						{ 
							header: '<h1>Thông báo!</h1><p>&nbsp;</p>', 
							life: 6000 
						}
					);
					break;
				case 'swithsu':
					$.jGrowl("<span class='success'>Lưu thông tin thành công.</span>", 
						{ 
							header: '<h1>Thông báo!</h1><p>&nbsp;</p>', 
							life: 6000 
						}
					);
					break;
				case 'postcontentok':
					$.jGrowl("<span class='success'>Nội dung đã được ghi nhận thành công, tạm thời thông tin mà bạn đăng lên đang trong trạng thái đợi kiểm duyệt.</span>", 
						{ 
							header: '<h1>Thông báo!</h1><p>&nbsp;</p>', 
							life: 6000 
						}
					);
					break;
				case 'postcontenterr':
					$.jGrowl("<span class='error'>Không thể ghi nhận thông tin mà bạn đăng lên. Xin vui lòng thử lại hoặc liên hệ với người quản trị.</span>", 
						{ 
							header: '<h1>Thông báo!</h1><p>&nbsp;</p>', 
							life: 6000 
						}
					);
					break;
				default:
					break;
			}
		}	
	}
}


// init process jscript.
$(function(){

	// handler widget admin tools toogles.
	$('div.widget-toolbar').each(function(){
		// clone widget tools template and put to the toolbar.
		$(this).html($(".widget-tools").html());
        // check for allow update.
		var allowEdit = $(this).parent().find('span.widget-allow-update').html();
		if(allowEdit != null && allowEdit == "")
			$(this).find('li.update').show();
		else
			$(this).find('li.update').hide();
	});
	
	// hook hover state.
	$('.ui-state-default').hover(
		function() { $(this).addClass('ui-state-hover'); },
		function() { $(this).removeClass('ui-state-hover'); 
	});
	
	// hook post new content click
	$("a[class='contentshref']").click(function(){
		var content = $(this).attr('rel');
		iSolus.postContents(content);
		return false;
	});
	
	// hook search box items.
	$(".defaultText").val($(".defaultText").attr('title'));		
	$(".defaultText").blur(function(){// blur.
		if($(this).val() != $(this).attr('title'))
		{
			$(this).val($(this).attr('title'));
			$(this).removeClass("defaultTextActive");
		}   					
	});				
	$(".defaultText").focus(function(){// default active text.
		if($(this).val() == $(this).attr('title')){
			$(this).addClass("defaultTextActive");
			$(this).val("");
		}
	});
	
	// handler login process	
	$("#password").val('');
	$("#username").val('');		
	$("#username").focus();
	
	$("#username").keyup(function(e) {
		if (e.keyCode == 13) {
			iSolus.doLogin();			
		}		
		return false;
	});
	$("#password").keyup(function(e) {
		if (e.keyCode == 13) {
			iSolus.doLogin();			
		}	
		return false;	
	});
	$(".btlogin").click(function(e) {
		iSolus.doLogin();		
		return false;
	});
	
	// top panel toggler process
	$("#toggle a").click(function () {
		$("#toggle a").toggle();
	});
	// Expand Panel
	$("#open").click(function(){
		$("div#panel").show();		
	});		
	// Collapse Panel
	$("#close").click(function(){
		$("div#panel").hide();			
	});	
	
	// sub menu admin bar handler
	$("ul.login li.admin").hover(
		function(){$(this).find("span").show();},
		function(){$(this).find("span").hide();}						
	);
	
	// add widget button click handler
	$(".btAddWidgets").click(function(){
		 iSolus.AddWidgetSubmition();
		 return false;
	});
	
	// add new page button click handler
	$(".btAddPages").click(function(){
		iSolus.AddPageSubmition();
		return false;
	});
			
});

