
/*
 * -------------------------------------
 * Document Ready
 * -------------------------------------
 */
$(document).ready(function() {

	var tree = Tree('#menu_categories ul');
	tree.init();

	// Purchase toggle
	if( $('.purchases_hide_toggle').length > 0 )
	{
		$('.purchases_hide_toggle').toggle(
			
			function(){
				$('#purchases_hide').slideUp(500);
			},
			function(){
				$('#purchases_hide').slideDown(500);
			}
		);

		$('.purchases_hide_toggle').click();
	}
	
});
 
/*
 * -------------------------------------
 * Object Declarations
 * -------------------------------------
 */

/*
 * Category handling functions
 *
 */
function Tree(className)
{
	var className 		= className;
	var toggleLock 		= false;
	var options 		= { path: '/', expires: 10 };

	if( null == $.cookie('category_open') )
	{
		$.cookie('category_open', ' ', options);
		$.cookie('category_open');
	}

	return {
		/*
		 * init
		 */
		init: function()
		{
			// Declare variables
			var self = this;
			
			$(className + ' li[id]').each(function(i){
				// Bind onclick
				$(this).bind("click", function(e){

					return self.toggle(this);
					
			    });

				if( '' != $.cookie('category_open') && null != $.cookie('category_open') )
				{
					// Open node if required
					var name = $(this).attr('id') + ',';
					if( $.cookie('category_open').indexOf(name) > -1 )
					{
						$(this).click();
						toggleLock = false;
					}
				}
			});
		},

		/*
		 * toggle
		 *
		 * Toggles a nodes children up or down depending on state
		 */
		toggle: function(node)
		{
			// Only proceed if toggleLock = false
			if( false == toggleLock )
			{
				if( 'children' == $(node).next().attr('class') )
				{
					if( $(node).next().is(':hidden') )
					{
						$(node).attr('class', 'open');
						$(node).next().slideDown(400);

						if( null != $.cookie('category_open') && -1 == $.cookie('category_open').indexOf($(node).attr('id') + ',') )
						{
							$.cookie('category_open', $.cookie('category_open') + $(node).attr('id') + ',', options);
						}
					}
					else
					{
						$(node).attr('class', '');
						$(node).next().slideUp(400);
						
						if( null != $.cookie('category_open') )
						{
							$.cookie('category_open', $.cookie('category_open').replace($(node).attr('id') + ',', ''), options);
						}
					}

					// Set toggleLock
					toggleLock = true;

					// Initiate timeout to clear toggleLock in 500 ms
					setTimeout(function(){
						toggleLock= false;
					}, 500);

					return false;
				}
				else
				{
					//window.location = return true;
					//return false;
				}
			}
		}
	}
}
	

/*
 * -------------------------------------
 * General Functions
 * -------------------------------------
 */
//Open Window Function:
function openwindow(theURL,winName,features, myWidth, myHeight, isCenter) { //v3.0

  if(window.screen)if(isCenter)if(isCenter=="true"){

	var myLeft = (screen.width-myWidth)/2;
    var myTop = (screen.height-myHeight)/2;
    features+=(features!='')?',':'';
    features+=',left='+myLeft+',top='+myTop;
  
  }

  newWindow = window.open(theURL,winName,features+((features!='')?',':'')+'width='+myWidth+',height='+myHeight);
  newWindow.focus()

}


function confirmreselect(url)
{
	
  var reselectMb = confirm("Warning: If you proceed to Select a new motherboard all configurations for you system will be lost: Continue?");

  if (reselectMb==true){
	  
    window.location.href="http://www.vtechindustries.com.au/sys_builder/index.php";

  }

}


//===================================================
// Post Data Functions - 
//===================================================

function getHTMLFieldPostData(){

    var postdata='';
    var inputFields = document.getElementsByTagName('input');
    var textAreas = document.getElementsByTagName('textarea');
    var menuLists = document.getElementsByTagName('select');
    var radiogroup = document.getElementsByTagName('radiogroup');

    //Get All Textfields:
    for (i=0;i<inputFields.length;i++) {
      if (inputFields[i].getAttribute('usrat_include') == "true" || inputFields[i].getAttribute('usrat_include_req') == "true"){
	    if(inputFields[i].getAttribute('type') == "text")
          postdata += inputFields[i].getAttribute('id')+"="+escapeChars(inputFields[i].value)+"&";
        if(inputFields[i].getAttribute('type') == "checkbox"){
          postdata += inputFields[i].getAttribute('id')+"="+inputFields[i].checked +"&";
		  
		}
      }
    }
	
    //Get All Textareas:
    for (i=0;i<textAreas.length;i++) {
      if (textAreas[i].getAttribute('usrat_include') == "true" || textAreas[i].getAttribute('usrat_include_req') == "true")
        postdata += textAreas[i].getAttribute('id')+"="+textAreas[i].value+"&";
    }

    //Get All Menu Lists:
    for (i=0;i<menuLists.length;i++) {
      if (menuLists[i].getAttribute('usrat_include') == "true" || menuLists[i].getAttribute('usrat_include_req') == "true")
        postdata += menuLists[i].getAttribute('id')+"="+menuLists[i].value+"&";
    }

    return postdata;
}


function checkHTMLFieldPostData(){
    var emptyData ='';
    var inputFields = document.getElementsByTagName('input');
    var textAreas = document.getElementsByTagName('textarea');
    var menuLists = document.getElementsByTagName('select');
    var radiogroup = document.getElementsByTagName('radiogroup');

    //Get All Text Fields:
    for (i=0;i<inputFields.length;i++) {
 	  //Check For Null
	  if (inputFields[i].getAttribute('usrat_include_req') == "true" || inputFields[i].getAttribute('usrat_req') == "true"){
        if(inputFields[i].value==null || inputFields[i].value == '')
          emptyData += "- "+inputFields[i].getAttribute('usrat_req_name')+',\n';
      }
	  
	  //Check for Email:
      if (inputFields[i].getAttribute('usrat_email') == "true"){
		  if(isValidEmail(inputFields[i].value) == false){
				emptyData += "- "+inputFields[i].getAttribute('usrat_req_name')+' (Not Valid Email),\n';
		  }
	  }
	  
	  //Check for Password Confirm:
      if (inputFields[i].getAttribute('usrat_confirm') == "true"){
		  if(inputFields[i].value != document.getElementById(inputFields[i].getAttribute('id')+'_confirm').value){
				emptyData += "- Confirmation "+inputFields[i].getAttribute('usrat_req_name')+'s not the same,\n';
		  }
	  }
    }
	
    //Get All Text Areas:
    for (i=0;i<textAreas.length;i++) {
      if (textAreas[i].getAttribute('usrat_include_req') == "true" || textAreas[i].getAttribute('usrat_req') == "true"){
        if(textAreas[i].value==null || textAreas[i].value == '')
          emptyData += "- "+textAreas[i].getAttribute('usrat_req_name')+',\n';
      }
    }

    //Get All Menu Lists:
    for (i=0;i<menuLists.length;i++) {
      if (menuLists[i].getAttribute('usrat_include_req') == "true" || menuLists[i].getAttribute('usrat_req') == "true"){
        if(menuLists[i].value==null || menuLists[i].value == '')
          emptyData += "- "+menuLists[i].getAttribute('usrat_req_name')+',\n';
      }
    }
    if (emptyData != '') {
        emptyData = emptyData.substr(0,emptyData.length-2);
        alert("Insufficient fields filled out:\n"+emptyData+"");
		return false;
		exit(0);
    }else
	return true;
}

function isValidEmail(email)
{
  var result = false;
  var theStr = new String(email);
  var index = theStr.indexOf("@");
  if (index > 0)
  {
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
  result = true;
  }

  return result;
}

function isPasswordValidMatch(id_one, id_two) {

    var validPassword = true;
	
    // Check to make sure that the full name field is not empty.
	if (document.getElementById(id_one).value != document.getElementById(id_two).value)
	{
		alert("Passwords Do Not Match. Please Re-Enter");
		validPassword = false;
	}

	return validPassword;
	
}


function escapeChars(temp_string){

	temp_string = temp_string.replace("'","");

	return temp_string;

}

function formWarrantyValidate() {
  var validWarranty = false;
  var alert_text = '';
  // Check to make sure that the full name field is not empty.
  if (document.warranty.first_name.value == "")
    alert_text = 'First Name\n';
  if (document.warranty.surname.value == "")
    alert_text = alert_text+'Surname\n';
  if (!isValidEmail(document.warranty.email.value))
    alert_text = alert_text+'Email\n';
  if (document.warranty.product_name.value == "")
    alert_text = alert_text+'Product Code/Name\n';
  if (document.warranty.description.value == "")
    alert_text = alert_text+'Description Name\n';
  if (document.warranty.invoice_number.value == "")
    alert_text = alert_text+'Invoice Number\n';
  if (document.warranty.invoice_date.value == "")
    alert_text = alert_text+'Invoice Date\n';

  if(alert_text!='')
    alert('Please Correct The Following Fields:\n\n'+alert_text+'\n');
  else{
	if (document.warranty.ack_1.checked == false)
      alert('Please Acknowlege Condition 1');
    else{ if (document.warranty.ack_2.checked == false)
           alert('Please Acknowlege Condition 2');
		 else{ if (document.warranty.ack_3.checked == false)
                alert('Please Acknowlege Condition 3');
              else{ if (document.warranty.ack_4.checked == false)
                     alert('Please Acknowlege Condition 4');
					else
                          validWarranty = true;
		      }
		 }
	}
  }
  return validWarranty;
}


//===================================================
// Set Attribute Functions
//===================================================

function setAttributeUniversal(id,attribute,value){
	
	document.getElementById(id).setAttribute(attribute,value);	

}

function hideShowImage(id, cat)
{
	
	document.getElementById("image_preview").setAttribute("src","http://www.vtechindustries.com.au/imagesProduct/"+cat+"/"+id+".jpg");

}

//===================================================
// Hide / Show Functions
//===================================================

function showHideExpandMinimize(id){

	var current_status = document.getElementById(id).getAttribute('expanded');
	
	if(current_status=='true'){

		document.getElementById(id).setAttribute('src','images/template/arrow_down.png');
		document.getElementById(id).setAttribute('expanded','false');

	}else{
  
		document.getElementById(id).setAttribute('src','images/template/arrow_down.png');
		document.getElementById(id).setAttribute('expanded','true');

	}  

}

function showHideExpandMinimizeWithPost(id){

	var current_status = document.getElementById(id+'_show_hide').getAttribute('expanded');

	if(current_status=='true'){

		document.getElementById(id).setAttribute('src','images/admin/button_minimize_dash_grey.png');
		document.getElementById(id).setAttribute('expanded','false');

		var response = universalPostToServer('/scripts/post_data/post_data_admin.php','updateadminselections','id='+id+'&action=add');
		
	}else{

		document.getElementById(id).setAttribute('src','images/admin/button_expand_cross_green.png');
		document.getElementById(id).setAttribute('expanded','true');

		var response = universalPostToServer('/scripts/post_data/post_data_admin.php','updateadminselections','id='+id+'&action=remove');

	}

}


//===================================================
// Disable Screen
//===================================================
function disableScreen(status){

	//Disable Screen Layer
	objScreenLayer = document.getElementById("disable_screen");
    
	var objClassObject = new ClassObject(objScreenLayer);    
	
	if(status == true){
        
	    objClassObject.setVisibleForObject('visible');
		
	}else{
		
	    objClassObject.hideLayerStart();
		
	}

}

function showDatePickerLayer(id){
	
    //Date Layer
    objDateLayer = document.getElementById(id);
    
    var objClassObject = new ClassObject(objDateLayer);    
        
    objClassObject.setVisibleForObject('visible');

}


function hideDatePickerLayer(id){

    setTimeout("hideDatePickerLayerNow('" + id + "');",500);

}


function hideDatePickerLayerNow(id){
   
	objDateLayer = document.getElementById(id);
    
    var objClassObject = new ClassObject(objDateLayer);    
        
    objClassObject.hideLayerStart();

}

function disableScreen(status){

	//Disable Screen Layer
	objScreenLayer = document.getElementById("disable_screen");
    
	var objClassObject = new ClassObject(objScreenLayer);    
	
	if(status == true){
        
	    objClassObject.setVisibleForObject('visible');
		
	}else{
		
	    objClassObject.hideLayerStart();
		
	}

}


function submitDeadLink(prod_id){

	if(confirm("Are you sure this manufacturer's link is dead?")){

		window.location.href = "index.php?page_id=dead_link&msg=http://www.vtechindustries.com.au/vtech/index.php?page_id=product_info&id=" + prod_id;

	}

}

function onImageError( image )
{
	var _image = $(image);
		
	//_image.attr('onError', '');

	_image.attr('src', '/images/products/no_image.gif');
}