// JavaScript Document
var currentURL = self.location.href;
var adminURL = currentURL.lastIndexOf('admin');
adminURL = currentURL.substr(0, adminURL) + "admin/";
$(document).ready(function(){
	//disable all buttons in list-*.php such as delete, enable, disable
	$("#action :input[@name=action]").each(function(){
		$(this).attr("disabled", "disabled");
	});
	//add click event to "Clear Selected" button
	$("#clear").click(function(){
		$("#action :input[@name=action]").each(function(){
			$(this).attr("disabled", "disabled");
			selected = false;
		});
	});
	//add click event to all checkboxes in list-*.php
	$("#action :checkbox").click(function(){
		var checked = false;
		$("#action :checkbox").each(function(){
			if(($(this).attr("checked")) == true){
				checked = true;	
			}
		});
		if(checked){
			$("#action :input[@name=action]").each(function(){
				$(this).removeAttr("disabled");
			});	
		}else{
			$("#action :input[@name=action]").each(function(){
				$(this).attr("disabled", "disabled");
			});	
		}
	});
	//handle form submit
	$("#action").submit(function(){
		return confirmSelected();
	});
});

function NewWindow(mypage, myname, w, h, scroll, resizable, status) 
{
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable='+resizable+',status='+status+'';
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

// validate form
function validate(objForm, file, submitOnSuccess)
{
	$("#status").html('<img src="../images/admin/loading.gif" />&nbsp;<span class="gray">Validating Submission...</span>');
	$.ajax({
		type:"POST",
		url: file,
		data:getRequestBody(objForm),
		success:function(xml){
			if(xml == 0){
				if(submitOnSuccess == null){
					$("#status").html('<span class="green">Submission Valid! Processing...</span><br/>');
					objForm.submit();
				}else{
					$("#status").html('');
				}
			}else{
				$("#status").html('<span class="red">' + xml + '</span><br/>');
			}
		}
	});
}

function getRequestBody(fobj) { 
	 var str = ""; 
	 var ft = ""; 
	 var fv = ""; 
	 var fn = ""; 
	 var els = ""; 
	 for(var i = 0;i < fobj.elements.length;i++) { 
	  els = fobj.elements[i]; 
	  ft = els.title; 
	  fv = els.value; 
	  fn = els.name; 
	 switch(els.type) { 
	  case "text": 
	  case "hidden": 
	  case "password": 
	  case "textarea":
		case "file":

	  str += fn + "=" + encodeURI(fv) + "&"; 
	  break;  
	 
	  case "checkbox": 
	  case "radio": 
	   if(els.checked) str += fn + "=" + encodeURI(fv) + "&"; 
	  break;     
	 
	 	case "select-one":
	    str += fn + "=" + 
	    els.options[els.selectedIndex].value + "&"; 
		break;
		
	  case "select-multiple":
		
			for(j=0; j<els.length; j++)
			{
				if(els.options[j].selected)
				{
					str += fn + "=" + 
					els.options[j].value + "&";
				}
			}
			
	  break; 
	  } // switch 
	 } // for 
	 str = str.substr(0,(str.length - 1)); 
return str; 
}

// tell a friend
function emailThisPage(intSiteID)
{
	NewWindow('./emailThisPage.php', 'EmailThisPage', 520, 500, 1, 0);
	//alert(window.location);
}

//print this page
function printPage()
{
	var txtQueryString = window.location.search.substring(1);
	var txtPrint = (txtQueryString=="")?'?print=1':'&print=1';
	NewWindow(window.location + txtPrint, 'PrintPage', 680, 500, 1, 1, 0);
}

function confirmSelected()
{
	return confirm('Are you sure you want to perform the actions on the selected items?');
}

// get files for folder with id = intFolderID
function getFiles(intFolderID, txtExtension, selectName) // txtExtension: image, file or flash 
{
	$('#imageHolder').html('<p>Please select an image from the drop down select.</p>');
	$.ajax({
		type:"GET",
		url:adminURL+'ajax/getpreviewimage.php',
		data:'intFolderID='+intFolderID+'&txtExtension='+txtExtension+'&selectName='+selectName,
		success:function(xml){
			$('#filelist').html(xml);
		}
	});
}

//display image when selected
function displayIntroImage(intFileID)
{
	$('#imageHolder').html('<img src="'+adminURL+'imageresize.inc.php?id='+ intFileID + '&w=140&h=140" />');
}

// build the category checkbox list 
function buildCategoryList(categoryList)
{
	$('#categoryContainer').html(categoryList);
}

// open add category popup
function addCategory()
{
	var intPageID = $("input:hidden[@name=intPageID]").val();
	if(intPageID == null){
		NewWindow('popup/addcategory.php', 'AddCategory', 400, 200, 1, 1, 0);
	}else{
		NewWindow('popup/addcategory.php?intPageID='+intPageID, 'AddCategory', 400, 200, 1, 1, 0);
	}
}

//when clicked, disable username field
function disableUsername(autoGenerate)
{	
	if(autoGenerate.checked)
	{
		$('#txtUsername').attr("disabled", "disabled");
		$('#txtUsername').attr("name", '');
	}
	else
	{
		$('#txtUsername').removeAttr("disabled");
		$('#txtUsername').attr("name", 'txtUsername');
	}
}

// add new folder popup
function addFolder(path)
{
	NewWindow(path+'/addFolder.php', 'AddFolder', 400, 200, 1, 1, 0);
}

// build the folder dropdown select menu
function buildFolderList(folderlist)
{
	$('#folderSelectContainer').html(folderlist);
}

// add a child element to the given parent element 
function addChildToParent(parentid){
		
		var parent = $('#'+parentid);

		var numberofchild = $('#numberofchild');
		var numberofchildi = ($('#numberofchild').val() - 1) + 2;
		numberofchild.value = numberofchildi;
	
		var li = $('<li id="child'+numberofchildi+'"></li>');
		
		// change the childHTML to the HTML code you need
		var childHTML = '<input type="file" name="arrFiles[]" size="50" /> ';
		
		li.html(childHTML + '<a title="remove" href="javascript:void(0)" onclick="removeChildFromParent('+"'"+parentid+"','child"+numberofchildi+"'"+')">remove</a>');
		parent.append(li);
}

// removes a child element from the given parent element
function removeChildFromParent(parentid, childid) {
	$("#"+childid).remove();
}

//close retrievePassword popup
function closePopup()
{
	$('#txtForgotUsername').val('');
	$('#pwdStatus').html('');
	$('#forgotPasswordWindow').hide();
}
//open retrievePassword popup
function openPopup()
{
	$('#forgotPasswordWindow').show();
}
//retrievePassword
function retreivePassword()
{
	$('#pwdStatus').ajaxStart(function(){
		$(this).html('<img src="../images/admin/loading.gif" />&nbsp;<span class="red">Validating Submission...</span>');
	});
	$.ajax({
		type:"POST",
		url:"retreivepassword.php",
		data:'txtForgotUsername=' + $('#txtForgotUsername').val(),
		success:function(xml){
			if(xml == 0){
				$('#pwdStatus').html('<span class="green">Your password has been send to your email.</span>');	
			}else{
				$('#pwdStatus').html('<span class="red">' + xml + '</span><br/>');
			}
		}
	});
}

function foldcategory(id, alink){
	if(alink.innerHTML == '[-]'){
//		$(id).hide();
		$(alink).parent().parent().next().hide();
		$(alink).parent().parent().next().next().hide();		
		alink.innerHTML = '[+]';
	}else{
//		$(id).show();
		$(alink).parent().parent().next().show();
		$(alink).parent().parent().next().next().show();		
		alink.innerHTML = '[-]';
	}
}

function foldpage(aclass, alink){
	if(alink.innerHTML=='[-]'){
		$("#sitemap "+aclass).each(function(){
			$(this).hide();						   
		});
		alink.innerHTML='[+]';
	}else{
		$("#sitemap "+aclass).each(function(){
			$(this).show();						   
		});
		alink.innerHTML='[-]';
	}
}
function swapPGOrder(current, intGroupID, direction){
	switch(direction){
		case "up":
			cid = current.attr("id");
			var preview = current.prev();
			var nid = preview.attr("id");
			$.ajax({
				type:"GET",
				url:"ajax/catalogue/swappg.php",
				data:"cid="+cid+"&nid="+nid+"&direction="+direction,
				success:function(xml){
					var godown = current.children().children().slice(1,2).html();
					var goup = current.prev().children().children().slice(2,3).html();
					if(xml == 0){
						if(current.next().html() == null){
							//last element
//							var godown = current.children().children().slice(1,2).html();
							godown = godown.replace(/up/g, "down");
							current.children().children().slice(2,3).html(godown);//enable go down after move down
							current.prev().children().children().slice(2,3).html("-");//previous one disable move down
						}
						if(current.prev().prev().html() == null){
							//to be first element
							//var goup = current.prev().children().children().slice(2,3).html();
							goup = goup.replace(/down/g, "up");
							current.prev().children().children().slice(1,2).html(goup);//previous enable goup
							current.children().children().slice(1,2).html("-");//disable move up
						}
						current.prev().before(current);
					}
				}
			});
		break;
		case "down":
			cid = current.attr("id");
			var preview = current.next();
			var nid = preview.attr("id");
			$.ajax({
				type:"GET",
				url:"ajax/catalogue/swappg.php",
				data:"cid="+cid+"&nid="+nid+"&direction="+direction,
				success:function(xml){
					var goup = current.children().children().slice(2,3).html();
					var godown = current.next().children().children().slice(1,2).html();
					if(xml==0){
						if(current.prev().html() == null){
//							var goup = current.children().children().slice(2,3).html();
							goup = goup.replace(/down/g, "up");
							current.children().children().slice(1,2).html(goup);
							current.next().children().children().slice(1,2).html("-");		
						}
						if(current.next().next().html() == null){
//							var godown = current.next().children().children().slice(1,2).html();
							godown = godown.replace(/up/g, "down");
							current.next().children().children().slice(2,3).html(godown);
							current.children().children().slice(2,3).html("-");		
						}
						current.next().after(current);
					}
				}
			});
		break;
	}
}
function confirmRemoveGroup(current, intGroupID){
	var con = confirm("Do you want to remove the group?");
	if(con){
		$.ajax({
			type:"GET",
			url:"ajax/catalogue/deletegroup.php",
			data:"intGroupID="+intGroupID,
			success:function(xml){
					if(xml == 0){
						current.remove();
					}
				}
		});
	}else{
		return false;
	}
}
function confirmRemoveProduct(current, intProductID){
	var con = confirm("Do you want to remove the product?");
	if(con){
		$.ajax({
			type:"GET",
			url:"ajax/catalogue/deleteproduct.php",
			data:"intProductID="+intProductID,
			success:function(xml){
				var parent = current.parent();
				if(xml == 0){
					current.remove();					
					if(parent.children().size() == 0 ){
						var id = parent.parent().attr("id");
						var newHtml = '<a href="javascript:void(0)" title="Remove category" onclick="confirmRemoveGroup($(this).parent().parent().parent(), \''+id+'\')">remove</a>';
						parent.parent().children().children().slice(4,5).html(newHtml);
						parent.parent().children().children().slice(0,1).html('&nbsp;');
					}
				}
			}
		});
	}else{
		return false;
	}
}
function confirmRemovePlaspakProduct(current, intProductID){
	var con = confirm("Do you want to remove the product?");
	if(con){
		$.ajax({
			type:"GET",
			url:"ajax/catalogue/deleteplaspakproduct.php",
			data:"intProductID="+intProductID,
			success:function(xml){
				var parent = current.parent();
				if(xml == 0){
					current.remove();					
					if(parent.children().size() == 0 ){
						var id = parent.parent().attr("id");
						var newHtml = '<a href="javascript:void(0)" title="Remove category" onclick="confirmRemoveGroup($(this).parent().parent().parent(), \''+id+'\')">remove</a>';
						parent.parent().children().children().slice(4,5).html(newHtml);
						parent.parent().children().children().slice(0,1).html('&nbsp;');
					}
				}
			}
		});
	}else{
		return false;
	}
}
function buildGroupList(html){
	$("#groupselect").html(html);	
}
function swapProductOrder(current, intProductID, direction){
	switch(direction){
		case "up":
			cid = current.attr("id");
			var preview = current.prev();
			var nid = preview.attr("id");
			$.ajax({
				type:"GET",
				url:"ajax/catalogue/swapproduct.php",
				data:"cid="+cid+"&nid="+nid+"&direction="+direction,
				success:function(xml){
					var godown = current.children().children().slice(1,2).html();
					var goup = current.prev().children().children().slice(2,3).html();
					if(xml == 0){
						if(current.next().html() == null){
							//last element
							var godown = current.children().children().slice(1,2).html();
							godown = godown.replace(/up/g, "down");
							current.children().children().slice(2,3).html(godown);//enable go down after move down
							current.prev().children().children().slice(2,3).html("-");//previous one disable move down
						}
						if(current.prev().prev().html() == null){
							//to be first element
							//var goup = current.prev().children().children().slice(2,3).html();
							goup = goup.replace(/down/g, "up");
							current.prev().children().children().slice(1,2).html(goup);//previous enable goup
							current.children().children().slice(1,2).html("-");//disable move up
						}
						current.prev().before(current);
					}
				}
			});
		break;
		case "down":
			cid = current.attr("id");
			var preview = current.next();
			var nid = preview.attr("id");
			$.ajax({
				type:"GET",
				url:"ajax/catalogue/swapproduct.php",
				data:"cid="+cid+"&nid="+nid+"&direction="+direction,
				success:function(xml){
					var goup = current.children().children().slice(2,3).html();
					var godown = current.next().children().children().slice(1,2).html();
					if(xml==0){
						if(current.prev().html() == null){
							goup = goup.replace(/down/g, "up");
							current.children().children().slice(1,2).html(goup);
							current.next().children().children().slice(1,2).html("-");		
						}
						if(current.next().next().html() == null){
							godown = godown.replace(/up/g, "down");
							current.next().children().children().slice(2,3).html(godown);
							current.children().children().slice(2,3).html("-");		
						}
						current.next().after(current);
					}
				}
			});
		break;
	}	
}
function swapPlaspakProductOrder(current, intProductID, direction){
	switch(direction){
		case "up":
			cid = current.attr("id");
			var preview = current.prev();
			var nid = preview.attr("id");
			$.ajax({
				type:"GET",
				url:"ajax/catalogue/swapplaspakproduct.php",
				data:"cid="+cid+"&nid="+nid+"&direction="+direction,
				success:function(xml){
					var godown = current.children().children().slice(1,2).html();
					var goup = current.prev().children().children().slice(2,3).html();
					if(xml == 0){
						if(current.next().html() == null){
							//last element
							var godown = current.children().children().slice(1,2).html();
							godown = godown.replace(/up/g, "down");
							current.children().children().slice(2,3).html(godown);//enable go down after move down
							current.prev().children().children().slice(2,3).html("-");//previous one disable move down
						}
						if(current.prev().prev().html() == null){
							//to be first element
							//var goup = current.prev().children().children().slice(2,3).html();
							goup = goup.replace(/down/g, "up");
							current.prev().children().children().slice(1,2).html(goup);//previous enable goup
							current.children().children().slice(1,2).html("-");//disable move up
						}
						current.prev().before(current);
					}
				}
			});
		break;
		case "down":
			cid = current.attr("id");
			var preview = current.next();
			var nid = preview.attr("id");
			$.ajax({
				type:"GET",
				url:"ajax/catalogue/swapplaspakproduct.php",
				data:"cid="+cid+"&nid="+nid+"&direction="+direction,
				success:function(xml){
					var goup = current.children().children().slice(2,3).html();
					var godown = current.next().children().children().slice(1,2).html();
					if(xml==0){
						if(current.prev().html() == null){
							goup = goup.replace(/down/g, "up");
							current.children().children().slice(1,2).html(goup);
							current.next().children().children().slice(1,2).html("-");		
						}
						if(current.next().next().html() == null){
							godown = godown.replace(/up/g, "down");
							current.next().children().children().slice(2,3).html(godown);
							current.children().children().slice(2,3).html("-");		
						}
						current.next().after(current);
					}
				}
			});
		break;
	}	
}
function searchIt(keyword){
	if(keyword =='' || keyword=='enter keyword'){
		return false;	
	}
	return true;
}
// get all pages that exist under the selected categories
function getPages(objSelectedCategories)
{
	var txtSelectedCategories = "";	
//	ajax = makeInstance();
	
	for(j=0; j<objSelectedCategories.length; j++)
	{
		if(objSelectedCategories.options[j].selected)
		{
			txtSelectedCategories += "cid[]=" + objSelectedCategories.options[j].value + "&";					
		}
	}
	txtSelectedCategories = txtSelectedCategories.substr(0,(txtSelectedCategories.length - 1));
	$.ajax({
		type:"POST",
		url:"../admin/ajax/getpages.php",
		data:txtSelectedCategories,
		success:function(xml){
			$('#pagelist').html(xml);
		}
	});
}