// JavaScript Document
$(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");
		});
	});
	//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").ajaxStart(function(){
		$(this).html('<img src="../images/admin/loading.gif" /><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', 500, 375, 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) // txtExtension: image, file or flash 
{
	$('#imageHolder').html('<p>Please select an image from the drop down select.</p>');
	$.ajax({
		type:"GET",
		url:'ajax/getpreviewimage.php',
		data:'intFolderID='+intFolderID+'&txtExtension='+txtExtension,
		success:function(xml){
			$('#filelist').html(xml);
		}
	});
}

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


//display image when selected
function displayIntroImage(intFileID)
{
	$('#imageHolder').html('<img src="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="gray">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 MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function check(keyword, id) {
	if (keyword == "enter keyword" && id == "txtSearch")
	{
		document.getElementById(id).value = "";
	}
	if (keyword == "your email address" && id == "txtEmail")
	{
		document.getElementById(id).value = "";
	}
	if (keyword == "your name" && id == "txtName")
	{
		document.getElementById(id).value = "";
	}
	if (keyword == "username" && id == "txtUsername")
	{
		document.getElementById(id).value = "";
	}
	if (keyword == "password" && id == "txtPassword")
	{
		document.getElementById(id).value = "";
	}
}

function validateSubscription(formData, jqForm, options) { 
    // fieldValue is a Form Plugin method that can be invoked to find the 
    // current value of a field 
    // 
    // To validate, we can capture the values of both the username and password 
    // fields and return true only if both evaluate to true
		$('#txtEmail').css({ "background-color":"white" });
		$('#txtName').css({ "background-color":"white" });		
 
    var emailValue = $('input[@name=txtEmail]').fieldValue(); 
    var nameValue = $('input[@name=txtName]').fieldValue(); 
		var pass = true;
		var emailRegExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
    // usernameValue and passwordValue are arrays but we can do simple 
    // "not" tests to see if the arrays are empty 
    if (!emailValue[0] || emailValue[0] == "your email address" || !emailRegExp.test(emailValue[0])) { 
				$('#txtEmail').css({ "background-color":"#FFCC88" });
				pass = false;
    }
		if (!nameValue[0] || nameValue[0] == "your name") { 
				$('#txtName').css({ "background-color":"#FFCC88" });
				pass = false;
		}
		if (!pass) {
  	  return false;
		} else {
			$('#subscriptionResponse').html('<h1>Submitting...</h1><img src="images/loadingAnimation.gif" alt="Loading" />');
			$('#subscriptionResponse').fadeIn('slow');			
	    return true;			
		}
}
//-->

// pre-submit callback 
function showRequest(formData, jqForm, options) 
{ 
	$('input:text, select, textarea').attr('class','field');
	$('.status').html('');
	$('input:submit').attr('disabled', 1);
	
    return true;
} 

// post-submit callback 
function showResponse(responseJSON, statusText)  
{ 
	var response = eval(responseJSON); 
 
 	if (response.status == 1)
	{
		for (var i = 0; i < response.message.length; i++)
		{
			$('#' + response.message[i].id).siblings('span').html( response.message[i].msg ); // print error message
		}
	
		$('.processing').html('<span class="error">Please make sure all fields are filled out correctly.</span>');

	}
	else
	{
		$('.processing').html('<span class="green">' + response.message + '</span>');
		$('.processing').parents('form').clearForm();
	}
	$('input:submit').attr('disabled', 0);

}
