jQuery.extend({
   postJSON: function( url, data, callback) {
      return jQuery.post(url, data, callback, "json");
   }
});

var homePageObject;
var CurrentObject;
var StepsObject;
var acontentSwaper;
var modalWindow;
var CarbonCalculator;
function IsNumeric(input)
{   
	return (input - 0) == input && input.length > 0;
}
function determine_StyleSheet_Set()
{
  var viewportwidth;
  var viewportheight;
  var ResolutionType;
  var prefix;
  // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
  
  if (typeof window.innerWidth != 'undefined')
  {
    viewportwidth = window.innerWidth,
    viewportheight = window.innerHeight
  }
  // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
  else if (typeof document.documentElement != 'undefined'
  && typeof document.documentElement.clientWidth !=
  'undefined' && document.documentElement.clientWidth != 0)
  {
    viewportwidth = document.documentElement.clientWidth,
    viewportheight = document.documentElement.clientHeight
  }
  // older versions of IE
  else
  {
    viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
    viewportheight = document.getElementsByTagName('body')[0].clientHeight
  }
  if($.browser.msie)
  {
    prefix="ie_";
    if($.browser.version=="6.0")
    {
      prefix="ie6_";
    }
    if($.browser.version=="7.0")
    {
      prefix="ie7_";
    }
    if($.browser.version=="8.0")
    {
      prefix="ie7_";
    }
    if($.browser.version=="9.0")
    {
      prefix="ie7_";
    }
  }
  else
  {
    prefix="";
  }
  if(viewportwidth>=1024)
  {
    ResolutionType="1280x1024";
  }
  else if(viewportwidth>800 && viewportwidth <= 1024)
  {
    ResolutionType="1024x768";
  }
  else
  {
    ResolutionType="1024x768";
  }
  $("head").append("<link>");
    css = $("head").children(":last");
    css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "Styles/"+ResolutionType+"/"+prefix+"site.css"
    });   

}
/**
This is the section mentioned in the Code regardin the Native JS Object Instantiation
Using the ID in the Main Wrapper we can determine which JS section to Run.
In Most cases its just the Content Swapper.
*/
function show_error(errorID,ErrorText)
{
  $("#error_"+errorID).html(ErrorText);
}
function hide_field_error(errorID)
{
  $("#error_"+errorID).html("");
}

function determine_page_initiatialisation()
{
  if($("#home_default").length>0)
  {
    homePageObject=new homePage();
    homePageObject.init();
  }
  if($("#login_button").length>0)
  {
    setupLoginSection();
  }
  if(
	    $("#home_about_foneworx").length>0 || 
	    $("#home_about_people").length>0 || 
	    $("#home_carbonworx_card").length>0 ||
	    $("#home_carbonworx_youth").length>0 ||
	    $("#home_carbonwrox_nursery").length>0 ||
	    $("#home_carbonworx_news").length>0 ||
	    $("#home_About_our_trees").length>0 ||
	    $("#home_hegebe_study").length>0 ||
	    $("#home_partner_info").length>0 ||
	    $("#home_become_a_partner").length>0 ||
	    $("#home_suppliers").length>0 ||
	    $("#home_contactdetails").length>0 ||
	    $("#home_qanda").length>0 ||
	    $("#home_glossary").length>0 ||
	    $("#user_green_room").length>0 ||
	    $("#user_redeem_points").length>0 ||
	    $("#calculator_carbon_footprint").length>0 ||
	    $("#user_points_pool").length>0 ||
	    $("#user_certificate_view").length >0 ||
	    $("#tree_user_green_room").length >0 ||
	    /**
	    * @author Justin Bedser
	    * Description:Content Change Accoring to EXCO document.
	    * Date:24/07/2011
	    */
	    $("#home_background").length >0 ||
	    $("#home_trainingInformation").length >0 ||  $("#home_central_park").length >0
	  )
  {
    if($("#content_holder").length!=0 && $("#content_swap_footer").length!=0 && $("#content_blocks").length!=0)
   	{
   		acontentSwaper=new contentSwaper();
   		acontentSwaper.init();
   	}
  }
  if($("#home_become_partner_details").length>0)
  {
    if($("#content_holder").length!=0 && $("#content_swap_footer").length!=0 && $("#content_blocks").length!=0)
   	{
   		acontentSwaper=new contentSwaper();
   		acontentSwaper.init();
   	}
    if($("#btnSmsView").length!=0)
 		{
 		  acontentSwaper.addEvent('#btnSmsView','click',function()
 		  {
 		    show_modal_page("<div><img src='images/Common/diagram1.png'></div>",500,600);
 		  });
 		  
 		}
 		if($("#btnSmsView2").length!=0)
 		{
 		  acontentSwaper.addEvent('#btnSmsView2','click',function()
 		  {
 		    show_modal_page("<div><img src='images/Common/diagram2.png'></div>",300,540);
 		  });
 		}
  }
  if($("#home_central_park").length>0)
  {
      acontentSwaper.addEvent('#image6','click',function(event)
      {
                      doClick(event);
      });
  }

  if($("#register_options_selection").length>0)
  {
    $("#Submit_register_option").click(
    function()
    {
      hide_field_error("optionSelectError");
      if($(":radio[name='card_action']:checked").length==0)
      {
        show_error("optionSelectError","Please select a Registration Option.");
      }
      else
      {
        window.location="index.php?section=register&action=registration_type&registrationType="+$(":radio[name='card_action']:checked").attr("value");
      }
      
    });
  }
  else if($("#register_profile_entry").length >0)
  {
    CurrentObject=new ProfileEntry();
    CurrentObject.init("profile_entry");
  }
  else if($("#user_profile_details").length >0)
  {
    CurrentObject=new ProfileEntry();
    CurrentObject.init("profile_edit");  
  }
  else if($("#register_payment_option_select").length >0)
  {
    $("#registration_payment_options").submit(
    function()
    {
      hide_field_error("optionSelectError");
      if($(":radio[name='payment_option']:checked").length==0)
      {
        show_error("optionSelectError","Please select a Payment Option.");
        return false;
      }
      else
      {
        return true;
      }
      
    });
  }
  else if($("#register_track_card").length>0)
  {
    setupOrderTrack();
  }
  else if($("#user_green_room").length>0)
  {
    $("#carbon_option_select").change(function()
    {
      window.location=globalPagePath+"index.php?section=user&action=green_room&category="+$(this).attr("value");
    });
  }
  else if($("#user_redeem_points").length>0)
  {
    $("#carbon_option_select").change(function()
    {
      window.location=globalPagePath+"index.php?section=user&action=redeem_points&category="+$(this).attr("value");
    });
  }
  else if($("#points_purchase_form").length>0)
  {
    $("#rand_value").keyup(function()
    {
      $("#rand_value").parent().siblings("span").html("");
      $("#rand_value").parent().siblings("span").addClass("error");
      var currentValue=$("#rand_value").attr("value");
      var PointsValValue=$("#rand_value").attr("value");
      $("#points_value").html("<p class=\"TEXT_White_on_green_bg_16px\" style=\"width:500px;\">You will purchase <font style=\"width:200px;\" class=\"redeem_cost\">0 Points</font></p>");
      if(IsNumeric(currentValue)==false)
      {
        $("#rand_value").parent().siblings("span").html("Please enter a numeric value.");
        $("#rand_value").attr("value","");
        return;
      }
      else if(parseFloat(currentValue)<0)
      {
        $("#rand_value").parent().siblings("span").html("Please enter a positive valu.");
        $("#rand_value").attr("value","");
        return;
      }
      if(parseFloat(currentValue)>300.00)
      {
        $("#rand_value").parent().siblings("span").html("Transaction value cannot exceed R300");
        $("#rand_value").attr("value","");
        return;
      }
      PointsValValue=PointsValValue*10;
      $("#points_value").html("<p class=\"TEXT_White_on_green_bg_16px\" style=\"width:400px;\">You will purchase <font style=\"width:200px;\" class=\"redeem_cost\">"+PointsValValue+" Points</font></p>");
    });
    $("#purchase_points").submit(function()
    {
      if(GeneralRuleValidation())
      {
        return true; 
      }
      return false;
    });
  }
  else if($("#credit_card_details").length>0)
  {
    $("#credit_card_form").submit(function()
    {
      if(GeneralRuleValidation())
      {
        return true; 
      }
      return false;
    });
    
  }
  else if($("#user_password_change").length>0)
  {
    $("#password_change").submit(function()
    {
      $("#error").html();
      if(GeneralRuleValidation())
      {
        if($("#current_password").attr("value")!="")
        {
          if($("#new_password").attr("value")=="" || $("#confirm_password").attr("value")=="")
          {
            $("#error").html("Please make sure your New and Confirmation passwords are not empty.");
            return false;
          }
          if(($("#new_password").attr("value")!=$("#confirm_password").attr("value")))
          {
            $("#error").html("Please make sure your New and Confirmation passwords match.");
            return false;
          }
        }
        if($("#current_pin").attr("value")!="")
        {
          if($("#new_pin").attr("value")=="" || $("#confirm_pin").attr("value")=="")
          {
            $("#error").html("Please make sure your New and Confirmation pins are not empty.");
            return false;
          }
          if($("#new_pin").attr("value")!=$("#confirm_pin").attr("value"))
          {
            $("#error").html("Please make sure your New and Confirmation pins match.");
            return false;
          }
        }
        return true; 
      }
      return false;
    });
  }  
  else if($("#user_certificate_view").length>0)
  {
    acontentSwaper.addEvent("input[name='change_ownership']",'click',showchangeCertOwnerShip);
    acontentSwaper.addEvent("input[name='cert_name_change']",'click',changeCertOwnerShip);
  }
  else if($("#user_points_pool").length>0)
  {
    acontentSwaper.addEvent("input[name='transfere_points']",'click',showPointsTransfere);
  }
  else if($("#login_login_options").length>0)
  {
    $("#user_login").submit(function()
    {
      if(GeneralRuleValidation("#user_login"))
      {
        return true;
      }
      return false;
    });
    $("#tree_login").submit(function()
    {
      if(GeneralRuleValidation("#tree_login"))
      {
        return true;
      }
      return false;
    });
    $("#cell_number").keyup(function()
    {
      var cellval=$("#cell_number").attr("value");
      if(cellval.length==10 && cellval.substr(0,1)=='0')
      {
        $("#cell_number").attr("value","+27"+cellval.substr(1,cellval.length));
      }
    });
    
  }
  else if($("#home_contactdetails").length>0)
  {
    $("#infoForm").submit(function()
    {
        if(GeneralRuleValidation('#infoForm'))
        {
            return true;
        }
        return false;
    }
    );
  }
  else if($("#home_become_a_partner").length>0)
  {
		acontentSwaper.addEvent('#infoForm','submit',function()
 		  {
				if(GeneralRuleValidation('#infoForm'))
				{
				return true;
				}
				return false;
 		  });
  }
  else if($("#register_vbc").length>0)
  {
		$("#vbc_registration_form").submit(function()
		{
			if(GeneralRuleValidation("#vbc_registration_form"))
			{
			return true;
			}
			return false;
		});
  }
  else if($("#register_tree_selection").length >0 || $("#tree_user_purchase_trees").length >0)
  {
    CurrentObject=new TreeOnlySelection();
    CurrentObject.init();
  }
  else if($("#home_trainingInformation").length >0)
	{
		acontentSwaper.addEvent('#book_now','click',function()
	  {
	    BookingForm();
	  });
	}
  
  if($("#carbonworx_training").length >0)
	{
		$("#trainingBooking").click(
		function()
		{
			BookingForm();
		});
		$("#clickHereBooking").click(
		function()
		{
			BookingForm();
		});
	}
	if($("#parlotones_button").length>0)
	{
    $("#parlotones_button").mouseover(function()
    {
                $("#parlotones_button").addClass("parlotones_button_hover");
                $("#parlotones_button").removeClass("parlotones_button");
    });
    $("#parlotones_button").mouseout(function()
    {
                $("#parlotones_button").addClass("parlotones_button");
                $("#parlotones_button").removeClass("parlotones_button_hover");
    });          
	}

}

function BookingForm()
{
	var LinkRef=globalPagePath+"index.php?section=home&AJAXaction=training_booking_form";
  $.get(LinkRef,
  function(data)
  {
    if(data!="")
    {
      show_modal_page(data,574,704);
      $("#booking_step2").hide();
      trainingBookingActions();
    }
    else
    {
      show_modal_page("<P>Page not found, Please contact your Support Administrator</P>",344,425);
    }
  });
}

function trainingBookingActions()
{
	$("#cancel_booking").click(
	function()
	{
		$.modal.close();
	});
	
	$("#enquiry_form").submit(
	function()
	{
		if (GeneralRuleValidation() == true)
		{
			$("#booking_step1").hide();
			var numRows = $("#delegates").val();
			$("#delegateNames").attr('rows', numRows);
			$("#delegateCellNumbers").attr('rows', numRows);
			$("#delegateFoodPreferences").attr('rows', numRows);
			
//					var dynamicHeight = 160 + (17+(numRows*16));
//					$("#simplemodal-container").height(dynamicHeight);
//					$("#simplemodal-container").width(720);
//					$("#simplemodal-container").offset({left: 190});
			$("#booking_step2").show();
		}
		
		return false;
	});
	
	$("#delegate_form").submit(
	function()
	{
		var numRows = $("#delegates").val();
		
		var data = $("#delegateNames").val();
		var myStr = data.toString();
		var myArray = myStr.split("\n");
		var numElems = myArray.length;
  	if (numElems != numRows)
  	{
  		alert('Delegate Names do not match the amount of Delegates specified.');
  		$("#delegateNames").focus();
  		return false;
  	}
  	
  	var data = $("#delegateCellNumbers").val();
		var myStr = data.toString();
		var myArray = myStr.split("\n");
		var numElems = myArray.length;
  	if (numElems != numRows)
  	{
  		alert('Delegate Cell Numbers do not match the amount of Delegates specified.');
  		$("#delegateCellNumbers").focus();
  		return false;
  	}
  	
  	var data = $("#delegateFoodPreferences").val();
		var myStr = data.toString();
		var myArray = myStr.split("\n");
		var numElems = myArray.length;
  	if (numElems != numRows)
  	{
  		alert('Delegate Food Preferences do not match the amount of Delegates specified.');
  		$("#delegateFoodPreferences").focus();
  		return false;
  	}
  	
  	//ajax to send data
  	$.postJSON(globalPagePath+"index.php",{'section':'home','AJAXaction':'submit_booking_form','company_name':$("#companyName").val(),'postal_address':$("#postalAddress").val(),'vat_number':$("#vatNumber").val(),'contact_name':$("#contactName").val(),'email_address':$("#emailAddr").val(),'phone_number':$("#telNumber").val(),'cell_number':$("#cellNumber").val(),'fax_number':$("#faxNumber").val(),'delegates':$("#delegates").val(),'comment':$("#comment").val(),'delegate_names':$("#delegateNames").val(),'delegate_cell_numbers':$("#delegateCellNumbers").val(),'delegate_food_preferences':$("#delegateFoodPreferences").val()},
    function(data)
    {
      if(data.status==true)
      {
        alert('Thank you for your enquiry. You will be contacted shortly with\n more information regarding CarbonWorx Training Course');
        $.modal.close();
      }
      if(data.status==false)
      {
        
      }
    });
  	return false;
	});
}

function eftPrint()
{
	if($("#print_me").length==1)
	{
		$("#print_me").printArea();
	}
}
function IsNumeric(input)
{   
	return (input - 0) == input && input.length > 0;
}
function Validator()
{
  this.isInternationalFormatTel=function(valuetoTest)
  {
    if(this.isNumber(valuetoTest) && valuetoTest.length>7)
    {
      if(valuetoTest.substring(0,1)=="+")
      {
        return true;
      }
      return false
    }
    return false;
  }
  this.istelephoneNumber=function(valuetoTest)
  {
    if(this.isNumber(valuetoTest) && valuetoTest.length==10)
    {
      return true;
    }
    return false;
  }
  this.isNumber=function(valuetoTest)
  {
    if(valuetoTest=="")
    {
      return false;
    }
    else if(IsNumeric(valuetoTest))
    {
      return true;
    }
    return false;
  }
  this.isAlphaNumeric=function(valuetoTest)
  {
    var regex=/^[0-9a-zA-Z\s]+$/;
    if(regex.test(valuetoTest))
    {
      return true;
    }
    return false;
  }
  this.isIDnumber=function(valuetoTest)
  {
    if(this.isNumber(valuetoTest) && valuetoTest.length==13)
    {
      return true;
    }
    return false;
    
  }
  this.isvalidEmail=function(valueToTest)
  {
		var filter =/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
		//if it's valid email
		if(filter.test(valueToTest) && valueToTest!=""){
			return true;
		}
		//if it's NOT valid
		else{
			return false;
		}
  }
  this.isValidDate=function(valueToTest)
  {
    var filter = /^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/;
		//if it's valid email
		var regexTest=filter.test(valueToTest);
		if(regexTest==false || valueToTest=="")
		{
			return false;
		}
		else
		{
			return true;
		}
  }
  this.checkforblankfield=function(valueToTest)
  {
		if(valueToTest=="")
		{
			return false;
		}
		else 
		{
			return true;
		}
  }
  
  
}
function checkValidity(RuleName,ErrorField,valueToCheck)
{
  var hasError=false;
  var Validation=new Validator();
  if(RuleName=="alpha")
  {
    if(Validation.isAlphaNumeric(valueToCheck))
    {
      ErrorField.html("");
      ErrorField.removeClass("error");
    }
    else
    {
      ErrorField.html("Please enter a valid Alpha-Numeric value.");
      ErrorField.addClass("error");
      hasError=true;
    }
  }
  else if(RuleName=="number")
  {
    if(Validation.isNumber(valueToCheck))
    {
      ErrorField.html("");
      ErrorField.removeClass("error");
    }
    else
    {
      ErrorField.html("Please enter a valid number value.");
      ErrorField.addClass("error");
      hasError=true;
    }
  }
  else if(RuleName=="date")
  {
    if(Validation.isValidDate(valueToCheck))
    {
      ErrorField.html("");
      ErrorField.removeClass("error");
    }
    else
    {
      ErrorField.html("Please enter a valid Date.");
      ErrorField.addClass("error");
      hasError=true;
    }
  }
  else if(RuleName=="email")
  {
    if(Validation.isvalidEmail(valueToCheck))
    {
      ErrorField.html("");
      ErrorField.removeClass("error");
    }
    else
    {
      ErrorField.html("Please enter a valid Email.");
      ErrorField.addClass("error");
      hasError=true;
    }
  }
  else if(RuleName=="telno")
  {
    if(Validation.istelephoneNumber(valueToCheck))
    {
      ErrorField.html("");
      ErrorField.removeClass("error");
    }
    else
    {
      ErrorField.html("Please enter a valid telephone number.");
      ErrorField.addClass("error");
      hasError=true;
    }
  }
  else if(RuleName=="telnoint")
  {
    if(Validation.isInternationalFormatTel(valueToCheck))
    {
      ErrorField.html("");
      ErrorField.removeClass("error");
    }
    else
    {
      ErrorField.html("Please enter a valid international telephone number.");
      ErrorField.addClass("error");
      hasError=true;
    }
  }
  else if(RuleName=="idno")
  {
    if(Validation.isIDnumber(valueToCheck))
    {
      ErrorField.html("");
      ErrorField.removeClass("error");
    }
    else
    {
      ErrorField.html("Please enter a valid ID Number.");
      ErrorField.addClass("error");
      hasError=true;
    }
  }
  else if(RuleName=="cwcardnumber")
  {
    if(Validation.isNumber(valueToCheck))
    {
      ErrorField.html("");
      ErrorField.removeClass("error");
      if(valueToCheck.length<16)
      {
        ErrorField.html("Please make sure your card number is the correct length.");
        ErrorField.addClass("error");
        hasError=true;
      }
      else
      {
        ErrorField.html("");
        ErrorField.removeClass("error");
      }
    }
    else
    {
      ErrorField.html("Please enter a valid number value.");
      ErrorField.addClass("error");
      hasError=true;
    }
  }
  else if(RuleName=="emptyfield")
  {
		if(Validation.checkforblankfield(valueToCheck))
		{
			ErrorField.html("");
			ErrorField.removeClass("error");
		}
		else
		{
			ErrorField.html("The Enquiry Detail field may not be left empty.");
			ErrorField.addClass("error");
			hasError=true;
		}
  }
  return !hasError;
  
}
function GeneralRuleValidation(mainSelector)
{
  //Find ALL hidden Fields With the Name VALIDATION / validation
  //alpha = Alpha numeric Eg: ABC123abd#$%
  // number =Only Numbers Alowed Eg:1234567890
  // date = Only a Date Format Eg. yyyy-mm-dd
  // email =Only Email Eg. asdf@as.as
  // telno = Any Telephone Number String,Limits the Length to 10 chars Eg. 0112930000
  // telnoint = Any International Number  Eg. +27112930000
  // idno = ID number EG 8406065150089
  var ValidationHiddens;
  if(mainSelector==undefined)
  {
    ValidationHiddens=$(":input[name=validation]");
  }
  else
  {
    ValidationHiddens=$(mainSelector+" :input[name=validation]");
  }
  
  $(".form_addinfo").removeClass("error");
  $(".form_addinfo").html("");
  $(".form_addinfo").show();
  var hasError=false;
  for(var i=0;i<ValidationHiddens.length;i++)
  {
    //Now we have all the Rules for the Specific Group.
    //Now we have to do the Validation for the INPUT either as a sibling or CHILD of the current element Group
    //First Strip out Rule type
    var Rule=$(ValidationHiddens[i]).attr("value");
    Rule=Rule.split("_");
    if(Rule.length==2)
    {
      //Now We find the INPUT in question.
      var inputToCheck=$(ValidationHiddens[i]).siblings("div").find("input:visible,textarea:visible,select:visible");      
      var ErrorField=$(ValidationHiddens[i]).siblings("span");
      if(inputToCheck.length!=0 && inputToCheck!=undefined)
      {

        var InputValue="";
        if($(inputToCheck).attr("type")=='radio')
        {
          var RadioGroupName=$(inputToCheck).attr("name");
          
          if($("input[@name="+RadioGroupName+"]:checked").length>0)
          {
            InputValue=$("input[@name="+RadioGroupName+"]:checked").attr("value");
          }
          else
          {
            InputValue="";
          }
        }
        else
        {
          InputValue=$(inputToCheck).attr("value");
        }
        //Now we check the Rules 
        //yes_[suffix] - Needs to have a value
        //no_[suffix] - No Need for a value but if one exists...Then Validate the Value according to the suffix
        if(Rule[0]=="yes")
        {
          if(InputValue=="")
          {
            ErrorField.html("Please enter a valid value.");
            ErrorField.addClass("error");
            hasError=true;
          }
          else
          {
            //Validate Against The Validation Rules
            var Validation=new Validator();
            if(checkValidity(Rule[1],ErrorField,InputValue)==false)
            {
              hasError=true;
            }             
          }
        }
        else if(Rule[0]=="no")
        {
          if(InputValue!="")
          {
            if(checkValidity(Rule[1],ErrorField,InputValue)==false)
            {
              hasError=true;
            }
          }
          
        }
      }
    }
    
  }
  if(hasError==true)
  {
    return false;
  }
  else
  {
    return true;
  }
}
function setup_common_hover_events()
{
  $("#login_button").mouseover(function()
  {
    $("#login_button").addClass("login_button_hover");
    $("#login_button").removeClass("login_button");
  });
  $("#login_button").mouseout(function()
  {
    $("#login_button").removeClass("login_button_hover");
    $("#login_button").addClass("login_button");
  });
  $(".user_options_holder").find("div").mouseover(function()
  {
    if($(this).hasClass("small_green_button"))
    {
      $(this).addClass("small_green_button_hover");
      $(this).removeClass("small_green_button");
    }
  });
  $(".user_options_holder").find("div").mouseout(function()
  {
    if($(this).hasClass("small_green_button_hover"))
    {
      $(this).addClass("small_green_button");
      $(this).removeClass("small_green_button_hover");
    }
  });

  $(".news_button_holder").children("div").mouseover(function()
  {
    if($(this).hasClass("news_button"))
    {
      $(this).addClass("news_button_hover");
      $(this).removeClass("news_button");
    }
  });
  $(".news_button_holder").children("div").mouseout(function()
  {
    if($(this).hasClass("news_button_hover"))
    {
      $(this).addClass("news_button");
      $(this).removeClass("news_button_hover");
    }
  });
  $(".carbon_calc_items_wrap").children("div").mouseover(function()
  {
    if($(this).hasClass("carbon_calc_items_button"))
    {
      $(this).addClass("carbon_calc_items_button_hover");
      $(this).removeClass("carbon_calc_items_button");
    }
  });
  $(".carbon_calc_items_wrap").children("div").mouseout(function()
  {
    if($(this).hasClass("carbon_calc_items_button_hover"))
    {
      $(this).addClass("carbon_calc_items_button");
      $(this).removeClass("carbon_calc_items_button_hover");
    }
  });
}

$(document).ready( function() 
{
  determine_StyleSheet_Set();
  
  determine_page_initiatialisation();
  setup_common_hover_events();
  
  setupTEMPevents();
  
}); 
//NEW MENU JS FUNCTION
$(function() 
{
   //We initially hide the all dropdown menus
   
    $('#dropdown_nav li').find('.sub_nav').hide();
    $('#dropdown_nav li').find('.sub_sub_nav').hide();
   //When hovering over the main nav link we find the dropdown menu to the corresponding link.
   
    $('#dropdown_nav li').hover(function() 
    {
      //Find a child of 'this' with a class of .sub_nav and make the beauty fadeIn.
      if($.browser.msie && $.browser.version=="7.0")
      {
        $(this).find('.sub_nav').css({'left':'-40px'});
      }
      $(this).find('.sub_nav').fadeIn(100);
      
      if($(this).children("ul").is(".sub_sub_nav"))
      {
       // var tester=$(this).children("ul .sub_sub_nav");
       $(this).children("ul .sub_sub_nav").find("a").show();
       $(this).children("ul .sub_sub_nav").fadeIn(100);
      }
      
    }, 
    function() 
    {
        //Do the same again, only fadeOut this time.
        $(this).find('.sub_nav').fadeOut(50);
        if($(this).children("ul").is(".sub_sub_nav"))
        {
         // var tester=$(this).children("ul .sub_sub_nav");
         $(this).children("ul .sub_sub_nav").fadeOut(50);
        }
      
    });
});

if($.browser.msie)
{
  if($.browser.version=="7.0" || $.browser.version=="8.0" || $.browser.version=="9.0")
  {
    $(function() 
    {
    	var zIndexNumber = 1000;
    	$('div').each(function() {
    		$(this).css('zIndex', zIndexNumber);
    		zIndexNumber -= 5;
    	});
    });
  }
  
}


/*
Page Class file section.
*/
function load_greenroom_view(carbon_category_id,carbon_credit_id,carbon_type_id)
{
  var LinkRef=globalPagePath+"index.php?section=user&AJAXaction=view_tree_info_page&carbon_category_id="+carbon_category_id+"&carbon_credit_id="+carbon_credit_id+"&carbon_type_id="+carbon_type_id;
  $.get(LinkRef,
  function(data)
  {
    if(data!="")
    {
      show_modal_page(data,450,475);
    }
    else
    {
      show_modal_page("<P>Page not found, Please contact your Support Administrator</P>",344,425);
    }
  });
}
function showHowThisWorks()
{
  var LinkRef=globalPagePath+"index.php?section=user&AJAXaction=how_this_works";
  $.get(LinkRef,
  function(data)
  {
    if(data!="")
    {
      show_modal_page(data,200,650);
    }
    else
    {
      show_modal_page("<P>Page not found, Please contact your Support Administrator</P>",344,425);
    }
  });
}
function showTreePurchaseForm(carbon_type_id,category)
{
  var LinkRef=globalPagePath+"index.php?section=user&AJAXaction=redeem_tree_purchase_form&credit_type="+carbon_type_id+"&category="+category;
  $.get(LinkRef,
  function(data)
  {
    if(data!="")
    {
      show_modal_page(data,550,525);
      //INITIALISE THE FORM MANAGEMENT OBJECT
      CurrentObject=new tree_redemption_form();
      CurrentObject.init(category);
    }
    else
    {
      show_modal_page("<P>Page not found, Please contact your Support Administrator</P>",344,425);
    }
  });
}
function TreeOnlySelection()
{
  this.init=function()
  {
    $("#tree_1").hide();
    $("#tree_2").hide();
    $("#tree_3").hide();
    $("#submit_payment").hide();
    $("#registration_profile").submit(function()
    {
      if(GeneralRuleValidation())
      {
        return true; 
      }
      return false;
    });
    $("#tree_num").change(function()
    {
      if($("#tree_num").attr("value")=="")
      {
        $("#tree_1").hide();
        $("#tree_2").hide();
        $("#tree_3").hide();
         $("#submit_payment").hide();
      }
      else
      {
        $("#tree_1").hide();
        $("#tree_2").hide();
        $("#tree_3").hide();
        for(i=1;i<=parseInt($("#tree_num").attr("value"));i++)
        {
          $("#tree_"+i).show();
        }
        $("#submit_payment").show();
      }
      
    });
  }
}
function tree_redemption_form(category)
{
  
  this.init=function(category)
  {
    $("#submit_redemption").click(function()
    {
      $("#error").html("");
      if(CurrentObject.validate())
      {
        if(parseInt($("#carbon_option_quantity").attr("value"))==0)
        {
          $("#error").html("Please enter a valid quantity.");
          return;
        }
        if(parseInt($("#carbon_option_cost").attr("value"))>parseInt($("#user_credits").attr("value")))
        {
          $("#error").html("Cost exeeds credits in account.");
          return;
        }
        if($("#location_selection").attr("value")=="")
        {
          $("#error").html("Please select a location");
          return;
        }
        $.getJSON(globalPagePath+"index.php",{'section':'user','AJAXaction':'redeem_trees_purchase',"carbon_type_id":$("#carbon_type_id").attr("value"),"quantity":$("#carbon_option_quantity").attr("value"),"location":$("#location_selection").attr("value"),"category_id":category},
        function(data)
        {
          if(data.status==true)
          {
            $(".registration_form").hide();
            $("#user_redeem_tree_purchase_form").append("<p style=\"margin-top:50px;float:left;width:80%\" class=\"TEXT_White_on_green_bg_14px\">Transaction Successful.</p>");
            $("#user_redeem_tree_purchase_form").append("<input type=\"hidden\" id=\"redirect_on_close\" value=\"yes\" >");
          }
          if(data.status==false)
          {
            $(".registration_form").hide();
            $("#user_redeem_tree_purchase_form").append("<p style=\"margin-top:50px;float:left;width:80%\" class=\"TEXT_White_on_green_bg_14px\">Transaction Failed."+data.content+"</p>");
          }
        });
        
      }
       return;
    });
    $("#carbon_option_quantity").keyup(function(event)
    {
      var ErrorField=$(event.target).parent().siblings("span");
      if(IsNumeric(event.target.value))
      {
        if(event.target.value.substr(0,1)=="0" && event.target.value.length>1)
        {
          $(event.target).attr("value",event.target.value.substr(1,event.target.value.length));
        }
        var NumberVal=parseInt(event.target.value);
        if(NumberVal>0)
        {
          var newTotalCost=parseInt($("#carbon_option_cost_per_unit").attr("value"))*NumberVal;
          $("#carbon_option_cost").attr("value",newTotalCost);
          $("#cost_notify").text(newTotalCost+" Points");
          if(newTotalCost>parseInt($("#user_credits").attr("value")))
          {
            
            ErrorField.html("Cost exeeds credits in account.");
            ErrorField.addClass("error");
            $(event.target).attr("value",0);
            $("#carbon_option_cost").attr("value",0);
            $("#cost_notify").text("0 Points");
          }
        }
        else
        {
          ErrorField.html("Please enter a positive Value.");
          ErrorField.addClass("error");
          $(event.target).attr("value",0);
          $("#carbon_option_cost").attr("value",0);
          $("#cost_notify").text("0 Points");
        
        }
      }      
      else
      {
        ErrorField.html("Please enter a numeric value.");
        ErrorField.addClass("error");
        $(event.target).attr("value",0);
        $("#carbon_option_cost").attr("value",0);
        $("#cost_notify").text("0 Points");
      }
      
      
    });
  }
  this.validate=function()
  {
    return GeneralRuleValidation();
  }
}
function checkLinkedAccount(Numberval)
{
  $.getJSON(globalPagePath+"index.php",{'section':'register','AJAXaction':'check_isLinkedAccount','telno':Numberval},
  function(data)
  {
    if(data.status==true)
    {

    }
    if(data.status==false)
    {

    }
  });
}
function check_msisdn(Numberval)
{
  $("#is_linked").remove();
  $.getJSON(globalPagePath+"index.php",{'section':'register','AJAXaction':'check_msisdn','telno':Numberval},
  function(data)
  {
    if(data.status==true)
    {
      if(data.content.show_message==true)
      {
        $("#registration_profile").append("<input type=\"hidden\" id=\"can_submit\" name=\"can_submit\" value=\"no\">");
        show_modal_page("<p class=\"TEXT_White_on_green_bg_12px\">Please note.<br>The Cellphone Number "+Numberval+" was found on our system.<br>Click <a href=\"index.php?section=login&action=show_login_options\" >here</a> to login .</p>",200,300);
        $("#cellphone").after("<input type=\"hidden\" id=\"is_linked\" value=\"yes\" name=\"purchase_linked\">");
      }
      
    }
    if(data.status==false)
    {
      $("#can_submit").remove();
    }
  });
}
function check_reg_no(regno)
{
  $.getJSON(globalPagePath+"index.php",{'section':'register','AJAXaction':'check_companyRegNo','regNo':regno},
  function(data)
  {
    if(data.status==true)
    {
      $("#registration_profile").append("<input type=\"hidden\" id=\"can_submit\" name=\"can_submit\" value=\"no\">");
      show_modal_page("<p class=\"TEXT_White_on_green_bg_12px\">Please note.<br>The Company Registration number "+regno+" was found on our system.This will be a linked account purchase.</p>",200,300);
      $("#companyregno").after("<input type=\"hidden\" id=\"is_linked\" value=\"yes\" name=\"purchase_linked\">");
    }
    if(data.status==false)
    {
      $("#can_submit").remove();
    }
  });
}

function ProfileEntry()
{
  this.init=function(initialisationType)
  {
    if(initialisationType=="profile_entry")
    {
      
    }
    else if(initialisationType=="profile_edit")
    {
      
    }
    CurrentObject.SetupEvents(initialisationType);
    
  }
  this.SetupEvents=function(initialisationType)
  {
    if(initialisationType=="profile_entry")
    {
      $("#registration_profile").submit(function()
      {
        if(CurrentObject.validateProfile())
        {
          if($("#can_submit").length >0 )
          {
            var NumberVal="";
            if($("#cellphone").length>0)
            {
              Numberval=$("#cellphone").attr("value");
            }
            else
            {
              Numberval=$("#companyregno").attr("value");
            }
            show_modal_page("<p class=\"TEXT_White_on_green_bg_12px\">Please note.<br>The Cellphone Number "+Numberval+" was found on our system.<br>Click <a href=\"index.php?section=login&action=show_login_options\" >here</a> to login .</p>",200,300);
            return false;
          }
          return true; 
        }
        return false;
      });
      $("#companyregno").keyup(function(event)
      {
        check_reg_no($("#companyregno").attr("value"));
 
      });
      if($("#cellphone").attr("value")!="")
      {
        var validation=new Validator();
        if(validation.isInternationalFormatTel($("#cellphone").attr("value")))
        {
          check_msisdn($("#cellphone").attr("value"));
        }
      }
      $("#cellphone").keyup(function(event)
      {
        var validation=new Validator();
        if(validation.isInternationalFormatTel($("#cellphone").attr("value")))
        {
          check_msisdn($("#cellphone").attr("value"));
        }
 
      });
      $("#cellphone").blur(function(event)
      {
        var validation=new Validator();
        if(validation.isInternationalFormatTel($("#cellphone").attr("value")))
        {
          check_msisdn($("#cellphone").attr("value"));
        }
 
      });
      $(":radio[name='delivery_option']").click(function(event)
      {
        var ItemID=event.target.id;
        ItemID=ItemID.substr(15,ItemID.length);
        var deliveryCost=$("#delivery_"+ItemID).attr("value");
        if(deliveryCost==0)
        {
          $("#delivery_wrap").slideUp("fast");
          $("#delivery_location_physical").attr("checked",false);
          $("#delivery_location_postal").attr("checked",true);
        }
        else
        {
          $("#delivery_wrap").slideDown("fast");
          $("#delivery_location_physical").attr("checked",false);
          $("#delivery_location_postal").attr("checked",false);
        }
        
      });
      
      
    }
    else if(initialisationType=="profile_edit")
    {
      $("#user_profile").submit(function()
      {
        if(CurrentObject.validateProfile())
        {
          return true; 
        }
        return false;
      });
    }
  }
  this.validateProfile=function()
  {
    return GeneralRuleValidation();
  }
  
}
function setupOrderTrack()
{
  $("#corporate,#individual").hide();
  $(":radio[name='Account_type']").click(function(event)
  {
    if($(event.target).attr("value")=='individual')
    {
      $("#corporate").hide(
      function()
      {
          $("#individual").show();
       
      });
    }
    else if($(event.target).attr("value")=='corporate')
    {
      $("#individual").hide(
      function()
      {
          $("#corporate").show();
      });
    }
    
  });
  $("#registration_track_card").submit(
  function()
  {
    hide_field_error("optionSelectError");
    if($(":radio[name='Account_type']:checked").length==0)
    {
      if($(":radio[name='Account_type']:checked").attr("value")=="individual" && $("#cellphone_number").attr("value")=="")
      {
        show_error("optionSelectError","Please enter your Cellphone number");
        return false;
      }
      else if($(":radio[name='Account_type']:checked").attr("value")=="individual" && $("#cellphone_number").attr("value")!="")
      {
        if(true)
        {
          return true;
        }
        else
        {
          show_error("optionSelectError","Please enter a valid Cellphone Number");
          return false;
        }
      }
      else if($(":radio[name='Account_type']:checked").attr("value")=="corporate")
      {
        
      }
      show_error("optionSelectError","Please select an Account Type.");
      return false;
    }
    else
    {
      return true;
    }
    
  });
}
/*######################################
      Login Functionality Block
#########################################*/
function hideLoginError()
{
  $("#error_section").fadeOut(100,function()
    {
      $("#error_section").find("span").html("");
      $("#registration_option").fadeIn(100);
    });
}
function showLoginError()
{
  $("#registration_option").fadeOut(100,function()
  {
    $("#error_section").fadeIn(100);
  });
}

function setupLoginSection()
{
  var timer;
  $("#login_button").click(function()
  {
    var HasError=false;
    if($("#cardnumber").attr("value")=="")
    {
      $("#error_section").find("span").html("Please enter a card number.");
      showLoginError();
      timer=setTimeout(hideLoginError,2000);
      HasError=true;
    }
    else if(IsNumeric($("#cardnumber").attr("value"))==false)
    {
      $("#error_section").find("span").html("Please enter a valid card number.");
      showLoginError();
      timer=setTimeout(hideLoginError,2000);
      HasError=true;
    } 
    else if($("#password").attr("value")=="")
    {
      $("#error_section").find("span").html("Please enter your password.");
      showLoginError();
      timer=setTimeout(hideLoginError,2000);
      HasError=true;
    }  
    if(HasError==false)
    {
      $.getJSON(globalPagePath+"index.php",{'section':'login','AJAXaction':'login','cardnumber':$("#cardnumber").attr("value"),"password":$("#password").attr("value")},
      function(data)
      {
        if(data.status==true)
        {
          window.location="index.php?section=user";
        }
        if(data.status==false)
        {
          $("#error_section").find("span").html(data.content.error_description);
          showLoginError();
          timer=setTimeout(hideLoginError,2000);
        }
      });
    }
  });
}


/*######################################
      Login Functionality Block
#########################################*/
function homePage()
{
  this.init=function()
  {
    StepsObject=new CarbonWorxSteps();
    StepsObject.init();  
  }
}
function CarbonWorxSteps()
{
  this.currentStep=0;
  this.previousStep=0;
  this.nextStepMarginLeft="-40px";
  this.UnSelectedItems_StartingMarginLeft="-30px";
  this.UnSelectedItems_MarginLeft="-60px";
  this.SelectedItems_MarginLeft="-60px";
  this.SelectedItems_LeftLastStep="-45px";
  this.TimerRef;
  this.StartzIndex=100;
  this.init=function()
  {
    this.setupLayout();
    this.startTimer();
    this.setupEvents();
    this.JumpToStep(1);
  }
  this.setupLayout=function()
  {
    var stepDivs=$("#step_wrapper").children(".steps_small_img_holder");
    for(var i=0;i<stepDivs.length;i++)
    {
      stepNum=i+1;
      if(i>=1) /*Skip the first item*/
      {
        
        $(stepDivs[i]).css({'margin-left':StepsObject.UnSelectedItems_StartingMarginLeft});
        
      }
      $(stepDivs[i]).addClass("steps_"+stepNum+"_unselect");
    }
  }
  this.increaseStep=function()
  {
    StepsObject.previousStep=StepsObject.currentStep;
    if(StepsObject.previousStep>6)
    {
      StepsObject.previousStep=1;
    }
    if(StepsObject.previousStep==0)
    {
      StepsObject.previousStep=1;
    }
    StepsObject.currentStep++;
    if(StepsObject.currentStep>6)
    {
      StepsObject.currentStep=1;
    }
    if(StepsObject.currentStep==0)
    {
      StepsObject.currentStep=1;
    }
    StepsObject.JumpToStep(StepsObject.currentStep);
    StepsObject.startTimer();
  }
  this.JumpToStep=function(StepNumber)
  {
    StepsObject.currentStep=StepNumber;
    //Change to Small Image
    $("#step_"+StepsObject.previousStep).removeClass("steps_large_img_holder");
    $("#step_"+StepsObject.previousStep).addClass("steps_small_img_holder");
        
    $("#step_"+StepsObject.previousStep).removeClass("steps_"+StepsObject.previousStep+"_select");
    $("#step_"+StepsObject.previousStep).addClass("steps_"+StepsObject.previousStep+"_unselect");
    var stepDivs=$("#step_wrapper").children(".steps_small_img_holder");
    for(var i=0;i<stepDivs.length;i++)
    {
      stepNum=i+1;
      if(i>=1) /*Skip the first item*/
      {
        $(stepDivs[i]).css({'margin-left':StepsObject.UnSelectedItems_StartingMarginLeft});   
      }
    }

    //Change to Large Image Image
    var stepDivs=$("#step_wrapper").children(".steps_small_img_holder");
    var nextStep=StepNumber;
    var CurrentStepIndex=nextStep-1;
    if(StepNumber!=6)
    {
      for(var i=0;i<stepDivs.length;i++)
      {
        stepNum=i+1;
        if(i>=1 && stepNum!=StepNumber) /*Skip the first item*/
        {
          $(stepDivs[i]).css({'margin-left':StepsObject.UnSelectedItems_MarginLeft});
        }
      }
      $(stepDivs[nextStep]).css({'margin-left':StepsObject.nextStepMarginLeft});
      if(CurrentStepIndex!=0)
      {
        $(stepDivs[CurrentStepIndex]).css({'margin-left':StepsObject.SelectedItems_MarginLeft});
      }
    }
    else if(StepNumber==6)
    {
      var LastItem=stepDivs.length-1;
      for(var i=0;i<stepDivs.length;i++)
      {
        stepNum=i+1;
        if(i>=1 && i!=LastItem) /*Skip the first and last item*/
        {
          $(stepDivs[i]).css({'margin-left':StepsObject.UnSelectedItems_MarginLeft});
        }
      }
      
      $(stepDivs[LastItem]).css({'margin-left':StepsObject.SelectedItems_LeftLastStep});
    }
    
    
    
    $("#step_"+StepNumber).removeClass("steps_small_img_holder");
    $("#step_"+StepNumber).addClass("steps_large_img_holder");
    
    $("#step_"+StepNumber).removeClass("steps_"+StepNumber+"_unselect");
    $("#step_"+StepNumber).addClass("steps_"+StepNumber+"_select");
    
    //Get the Step text
    StepText=$("#step_"+StepNumber+" div").html();
    $("#step_information").html(StepText);
  }
  this.startTimer=function()
  {
    StepsObject.TimerRef=setTimeout(this.increaseStep,5000);
  }
  this.clearTimer=function()
  {
    clearTimeout(StepsObject.TimerRef);
  }
  this.setupEvents=function()
  {
    $(".steps_small_img_holder").unbind("click");
    $(".steps_small_img_holder").click(function(event)
    {
      StepsObject.clearTimer();
      StepsObject.startTimer();
      ItemId=event.target.id;
      stepNum=ItemId.substring(5,ItemId.length);
      StepsObject.previousStep=StepsObject.currentStep;
      StepsObject.JumpToStep(stepNum);
    });
  }
  
}
/*
Page Class file section.
*/
function openTermsModal(LinkRef)
{
  $.get(LinkRef,
  function(data)
  {
    if(data!="")
    {
      show_modal_page(data,344,425);
    }
    else
    {
      show_modal_page("<P>Page not found, Please contact your Support Administrator</P>",344,425);
    }
  });
  
}
function show_modal_page_unclosable(PageContent,minHeight_input,minWidth_input)
{
  	$("#modal_window").empty();
  $("#modal_window").html(PageContent);
  $("#modal_window").modal({onOpen:
    function (dialog)
    {
      dialog.overlay.fadeIn('fast', function () {
        dialog.data.hide();
        dialog.container.fadeIn('fast', function () {
          dialog.data.slideDown('slow');
        });
      });
      $("#close_cmd").remove();
    },onClose:
    function (dialog)
    {

    }
    ,minWidth:minWidth_input,minHeight:minHeight_input,maxWidth:minWidth_input,maxHeight:minHeight_input}); 
}
function show_modal_page(PageContent,minHeight_input,minWidth_input)
{
	$("#modal_window").empty();
  $("#modal_window").html(PageContent);
  $("#modal_window").modal({onOpen:
    function (dialog)
    {
      dialog.overlay.fadeIn('fast', function () {
        dialog.data.hide();
        dialog.container.fadeIn('fast', function () {
          dialog.data.slideDown('slow');
        });
      });
    },onClose:
    function (dialog)
    {
      var redirect=false;
      if($("#redirect_on_close").length>0)
      {
        redirect=true;
      }
      $("#modal_window").empty();
      dialog.overlay.fadeOut('fast', function () 
      {
        dialog.data.hide();
        dialog.container.fadeOut('fast', function () 
        {
          dialog.data.slideUp('fast');
          $.modal.close();
          $("#modal_window").empty();
          $("#modal_window").css({display:'none'});
          if(redirect)
          {
            window.location=window.location;
          }
        });
      });
    }
    ,minWidth:minWidth_input,minHeight:minHeight_input,maxWidth:minWidth_input,maxHeight:minHeight_input});  
}



//TEMPORARY section
//WILL REMOVE ONCe THE PAGES ARE PROPERLY INTEGRATED


function setupTEMPevents()
{  
  if($("#btnPartnerApply").length!=0)
  {
    $("#btnPartnerApply").click(
  	function()
  	{
      var modalInsert = "<p class=\"TEXT_White_on_green_bg_12px\" style=\"padding-left:1px\">Points Partner"+
          "<br />"+
          "<br />A points partner is associated with CarbonWorx on the basis<br/>that products are displayed on the CarbonWorx website and in<br/>certain instances on associated printed material in terms of<br/>which any CarbonWorx cardholder can purchase such<br/>product/service at an agreed discount rate.<br/>The discount is then converted to points and allocated to the cardholders CarbonWorx card."+
          "Partners who wish to<br/>participate in this programme would engage with a FoneWorx executive in terms of which the products would be identified as suitable to the profile of CarbonWorx and its objectives and, in addition thereto, the discount structure would be agreed to<br/>which would be passed on to the consumer when purchasing a product<br/>from such supplier on presentation of the CarbonWorx card."+
          "CarbonWorx passes on 100% of the discount to the cardholder. "+
          "Should a supplier of a service or product wish to participate in this program, they are requested to contact Catherine Edgar on:"+
          "<br />"+
          "<br />Tel:  (011) 293 0000"+
          "<br />Email:<a class='steps' href='mailto:cedgar@foneworx.co.za'>cedgar@foneworx.co.za</a></p>";
      $("#modal_window").empty();
      $("#modal_window").html(modalInsert);
  	  $("#modal_window").modal({onOpen: 
  		function (dialog)
   		{
  				dialog.overlay.fadeIn('fast', function () 
  				{
  					dialog.data.hide();
  					dialog.container.fadeIn('fast', function () 
  					{
  						dialog.data.slideDown('slow');
  					});
  				});
  		},onClose: 
  		function (dialog) 
   		{
  				dialog.overlay.fadeOut('fast', function () {
  					dialog.data.hide();
  					dialog.container.fadeOut('fast', function () 
  					{
  						dialog.data.slideUp('fast');
  						$.modal.close();
  						$("#modal_window").empty();
  						$("#modal_window").css({display:'none'});
  					});
  				});
  		}
  		,minWidth:460,minHeight:480,maxWidth:460,maxHeight:480});
    });
  }
  if($("#btnpointsPartnersInfo").length>0)
  {
    $("#btnpointsPartnersInfo").click(
  	function()
  	{
      var modalInsert = "<p class=\"TEXT_White_on_green_bg_12px\" style=\"padding-right:2px\">"+
                  "<br />"+
                  "Present your CarbonWorx card to one of our CarbonWorx points partners and receive a percentage discount on your spend, which is converted to points which can be redeemed for trees or food security products. "+
                  "Points are allocated to cards within 7 (seven) days after each calendar month (see terms and conditions)."+
                "<br /><br />"+
                  "<b>Individual Cards</b><br /> The CarbonWorx card is more than just a token, it identifies you as an individual who wants to make a difference. Purchasing a CarbonWorx card is a voluntary process to have a tree planted to help in the environmental impact on a micro and macro scale."+
                "<br /><br />"+
                  "The registered CarbonWorx cardholder can participate in additional programs to accrue further points through retailers and suppliers allowing the cardholder to plant additional trees and also increase their positive impact on the environment and surroundings."+
                "<br />"+
                  "The CarbonWorx user card is a passport that will soon be able to be used as a loyalty program token giving discounts, and additional accrual of points towards trees upon purchases."+
                 "</p>";
      $("#modal_window").empty();
      $("#modal_window").html(modalInsert);
  	  $("#modal_window").modal({onOpen: 
  		function (dialog)
   		{
  				dialog.overlay.fadeIn('fast', function () 
  				{
  					dialog.data.hide();
  					dialog.container.fadeIn('fast', function () 
  					{
  						dialog.data.slideDown('slow');
  					});
  				});
  		},onClose: 
  		function (dialog) 
   		{
  				dialog.overlay.fadeOut('fast', function () {
  					dialog.data.hide();
  					dialog.container.fadeOut('fast', function () 
  					{
  						dialog.data.slideUp('fast');
  						$.modal.close();
  						$("#modal_window").empty();
  						$("#modal_window").css({display:'none'});
  					});
  				});
  		}
  		,minWidth:460,minHeight:480,maxWidth:460,maxHeight:480});
    });
  }
  if(("#aboutavis_pointpartner").length>0)
  {
	try{
			 $("#aboutavis_pointpartner").click(
			function()
			{
			 var modalInsert = "<p class=\"TEXT_White_on_green_bg_12px\" style=\"padding-right:2px\">"+
			  "Avis Rent a Car, South Africa's leading Carbon Neutral accredited Car Rental Company, has partnered with Carbonworx to offer all members incredible car rental rates within South Africa.<br/><br/>"+
				"Avis has played an important leadership role and pioneered numerous innovations and processes in the industry over the past 40 years, positioning us as the leading car rental company in Southern Africa.  Today we continue to establish industry firsts and currently lead the way as the industry's greenest company.  We were the first to introduce Hybrid Vehicle technology in 2007. We are also the first company in South Africa to achieve CarbonNeutral&reg; accreditation for the offset of our CO2 emissions since 2008.  In addition, we are the first car rental company in SA to conduct intensive water recycling efforts and effectively become \"water neutral\" at our Western Cape and KZN operations in the wetter months, saving over 75-million litres of water per annum.<br/><br/>"+
				"At Avis, we offer you a Total Transport Solution that includes, short term car rental, Point 2 Point, Chauffer drive, Luxury Car rental, Van rentals and Coach Charter.<br/><br/>"+
				"Book online now or call our Reservations Centre on 0861 021 111."+
						 "</p>";
			  $("#modal_window").empty();
			  $("#modal_window").html(modalInsert);
			  $("#modal_window").modal({onOpen: 
				function (dialog)
				{
						dialog.overlay.fadeIn('fast', function () 
						{
							dialog.data.hide();
							dialog.container.fadeIn('fast', function () 
							{
								dialog.data.slideDown('slow');
							});
						});
				},onClose: 
				function (dialog) 
				{
						dialog.overlay.fadeOut('fast', function () {
							dialog.data.hide();
							dialog.container.fadeOut('fast', function () 
							{
								dialog.data.slideUp('fast');
								$.modal.close();
								$("#modal_window").empty();
								$("#modal_window").css({display:'none'});
							});
						});
				}
				,minWidth:460,minHeight:480,maxWidth:460,maxHeight:480});
			});
		}
		catch(error)
		{
		}
  }
  $("#image0").click(function(event)
  {
    doClick(event);
  });
  $("#image1").click(function(event)
  {
    doClick(event);
  });
  $("#image2").click(function(event)
  {
    doClick(event);
  });
  $("#image3").click(function(event)
  {
    doClick(event);
  });
  $("#image4").click(function(event)
  {
    doClick(event);
  });
  $("#image5").click(function(event)
  {
    doClick(event);
  });
  $("#image6").click(function(event)
  {
    doClick(event);
  });
  $("#link_0").click(function(event)
  {
    doClick(event);
  });
  $("#link_1").click(function(event)
  {
    doClick(event);
  });
  $("#link_2").click(function(event)
  {
    doClick(event);
  });
  $("#link_3").click(function(event)
  {
    doClick(event);
  });
  $("#link_4").click(function(event)
  {
    doClick(event);
  });
  $("#link_5").click(function(event)
  {
    doClick(event);
  });
  $("#link_6").click(function(event)
  {
    doClick(event);
  });
}
function doClick(event)
{
  var elemid=event.target.id;
  //alert(elemid);
  var imgNum=elemid.substring(5,elemid.length);
  var youTubeAccess = $('#youTubeAccess').val();
  var videoHTML = "";
  $("#modal_window").empty();
  $("#modal_window").html(videoHTML);  
  if (youTubeAccess == 1)
  {
    videoHTML = getVideo(imgNum);
  }
  else
  {
    videoHTML = getAltVideo(imgNum);
  }
  var Wrapper="<div style=\"width:400px;height:400px\">"+videoHTML+"</div>";
  show_modal_page(Wrapper,400,500);

}
function getAltVideo(num)
{
  var videoData;
  if (num == 0)
  {
    videoData = "<object id='music' height='360' width='370' classid='CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95' "+
                "codebase='https://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'"+
                "standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>"+
                "<param name='fileName' value='videos/CarbonworxAd.wmv' />"+
                "<param name='autostart' value='true'>"+
                "<param name='ShowStatusBar' value='1'/>"+
                "<param name='AudioStream' value='-1'/>"+
                "<param name='AutoSize' value='1'/>"+
                "<param name='AnimationAtStart' value='0'/>"+
                "<embed type='application/x-mplayer2' pluginspage='http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/' src='videos/CarbonworxAd.wmv' name='MediaPlayer' autostart='false' loop='false' height='340' width='370'></embed>"+
                "</object>";
  }
  if (num == 1)
  {
    videoData = "<object id='music' height='360' width='370' classid='CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95' "+
                "codebase='https://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'"+
                "standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>"+
                "<param name='fileName' value='videos/CarbonFree.wmv' />"+
                "<param name='autostart' value='true'>"+
                "<param name='ShowStatusBar' value='1'/>"+
                "<param name='AudioStream' value='-1'/>"+
                "<param name='AutoSize' value='1'/>"+
                "<param name='AnimationAtStart' value='0'/>"+
                "<embed type='application/x-mplayer2' pluginspage='http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/' src='videos/CarbonFree.wmv' name='MediaPlayer' autostart='false' loop='false' height='340' width='370'></embed>"+
                "</object>";
  }
  if (num == 2)
  {
    videoData = "<object id='music' height='360' width='370' classid='CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95' "+
                "codebase='https://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'"+
                "standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>"+
                "<param name='fileName' value='videos/SeeSaw.wmv' />"+
                "<param name='autostart' value='true'>"+
                "<param name='ShowStatusBar' value='1'/>"+
                "<param name='AudioStream' value='-1'/>"+
                "<param name='AutoSize' value='1'/>"+
                "<param name='AnimationAtStart' value='0'/>"+
                "<embed type='application/x-mplayer2' pluginspage='http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/' src='videos/SeeSaw.wmv' name='MediaPlayer' autostart='false' loop='false' height='340' width='370'></embed>"+
                "</object>";
  }
  if (num == 3)
  {
    videoData = "<object id='music' height='360' width='370' classid='CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95' "+
                "codebase='https://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'"+
                "standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>"+
                "<param name='fileName' value='videos/CarDrives.wmv' />"+
                "<param name='autostart' value='true'>"+
                "<param name='ShowStatusBar' value='1'/>"+
                "<param name='AudioStream' value='-1'/>"+
                "<param name='AutoSize' value='1'/>"+
                "<param name='AnimationAtStart' value='0'/>"+
                "<embed type='application/x-mplayer2' pluginspage='http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/' src='videos/CarDrives.wmv' name='MediaPlayer' autostart='false' loop='false' height='340' width='370'></embed>"+
                "</object>";
  }
  if (num == 4)
  {
    videoData = "<object id='music' height='360' width='370' classid='CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95' "+
                "codebase='https://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'"+
                "standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>"+
                "<param name='fileName' value='videos/CarbonWorx3minAd.wmv' />"+
                "<param name='autostart' value='true'>"+
                "<param name='ShowStatusBar' value='1'/>"+
                "<param name='AudioStream' value='-1'/>"+
                "<param name='AutoSize' value='1'/>"+
                "<param name='AnimationAtStart' value='0'/>"+
                "<embed type='application/x-mplayer2' pluginspage='http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/' src='videos/CarbonWorx3minAd.wmv' name='MediaPlayer' autostart='false' loop='false' height='340' width='370'></embed>"+
                "</object>";
  }
  if (num == 5)
  {
    videoData = "<object id='music' height='360' width='370' classid='CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95' "+
                "codebase='https://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'"+
                "standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>"+
                "<param name='fileName' value='videos/CarbonGiftCard.wmv' />"+
                "<param name='autostart' value='true'>"+
                "<param name='ShowStatusBar' value='1'/>"+
                "<param name='AudioStream' value='-1'/>"+
                "<param name='AutoSize' value='1'/>"+
                "<param name='AnimationAtStart' value='0'/>"+
                "<embed type='application/x-mplayer2' pluginspage='http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/' src='videos/CarbonGiftCard.wmv' name='MediaPlayer' autostart='false' loop='false' height='340' width='370'></embed>"+
                "</object>";
  }
  
  if (num == 6)
  {
    videoData = "<object id='music' height='360' width='370' classid='CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95' "+
                "codebase='https://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'"+
                "standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>"+
                "<param name='fileName' value='videos/sandtonTreePlanting.wmv' />"+
                "<param name='autostart' value='true'>"+
                "<param name='ShowStatusBar' value='1'/>"+
                "<param name='AudioStream' value='-1'/>"+
                "<param name='AutoSize' value='1'/>"+
                "<param name='AnimationAtStart' value='0'/>"+
                "<embed type='application/x-mplayer2' pluginspage='http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/' src='videos/sandtonTreePlanting.wmv' name='MediaPlayer' autostart='false' loop='false' height='340' width='370'></embed>"+
                "</object>";
  }
  
  
  return videoData;
}

function getVideo(num)
{
  var videoData;
  if (num == 0)
  {
    videoData = "<object height='340' width='370' classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'>"+
    "<param name='movie' value='Js/YTPlayer.swf?vidId=ql2HTmCEiC8' />"+
    "<param name='allowFullScreen' value='true' />"+
    "<param name='allowscriptaccess' value='always' />"+
    "<embed src='Js/YTPlayer.swf?vidId=ql2HTmCEiC8' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='425' height='344'></embed>"+
    "</object>"+
    "<br />"+
    "<p>If you cannot view this video <a href='#' onClick='changeVideo(0);'>Click Here</a></p>";
  }
  if (num == 1)
  {
    videoData = "<object height='340' width='370' classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'>"+
    "<param name='movie' value='Js/YTPlayer.swf?vidId=nLDiJNR2RKM' />"+
    "<param name='allowFullScreen' value='true' />"+
    "<param name='allowscriptaccess' value='always' />"+
    "<embed src='Js/YTPlayer.swf?vidId=nLDiJNR2RKM' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='425' height='344'></embed>"+
    "</object>"+
    "<br />"+
    "<p>If you cannot view this video <a href='#' onClick='changeVideo(1);'>Click Here</a></p>";
  }
  if (num == 2)
  {
    videoData = "<object height='340' width='370' classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'>"+
    "<param name='movie' value='Js/YTPlayer.swf?vidId=5qglRcRwNT8' />"+
    "<param name='allowFullScreen' value='true' />"+
    "<param name='allowscriptaccess' value='always' />"+
    "<embed src='Js/YTPlayer.swf?vidId=5qglRcRwNT8' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='425' height='344'></embed>"+
    "</object>"+
    "<br />"+
    "<p>If you cannot view this video <a href='#' onClick='changeVideo(2);'>Click Here</a></p>";
  }
  if (num == 3)
  {
    videoData = "<object height='340' width='370' classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'>"+
    "<param name='movie' value='Js/YTPlayer.swf?vidId=9SRDBYcpr2g' />"+
    "<param name='allowFullScreen' value='true' />"+
    "<param name='allowscriptaccess' value='always' />"+
    "<embed src='Js/YTPlayer.swf?vidId=9SRDBYcpr2g' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='425' height='344'></embed>"+
    "</object>"+
    "<br />"+
    "<p>If you cannot view this video <a href='#' onClick='changeVideo(3);'>Click Here</a></p>";
  }
  if (num == 4)
  {
    videoData = "<object height='340' width='370' classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'>"+
    "<param name='movie' value='Js/YTPlayer.swf?vidId=rcJAcjlyYco' />"+
    "<param name='allowFullScreen' value='true' />"+
    "<param name='allowscriptaccess' value='always' />"+
    "<embed src='Js/YTPlayer.swf?vidId=uV89QjIKiww' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='425' height='344'></embed>"+
    "</object>"+
    "<br />"+
    "<p>If you cannot view this video <a href='#' onClick='changeVideo(4);'>Click Here</a></p>";
  }
  if (num == 5)
  {
    videoData = "<object height='340' width='370' classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'>"+
    "<param name='movie' value='Js/YTPlayer.swf?vidId=ZRA419QQOMw' />"+
    "<param name='allowFullScreen' value='true' />"+
    "<param name='allowscriptaccess' value='always' />"+
    "<embed src='Js/YTPlayer.swf?vidId=ZRA419QQOMw' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='425' height='344'></embed>"+
    "</object>"+
    "<br />"+
    "<p>If you cannot view this video <a href='#' onClick='changeVideo(5);'>Click Here</a></p>";
  }
  
  if (num == 6)
  {
    videoData = "<object height='340' width='370' classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'>"+
    "<param name='movie' value='Js/YTPlayer.swf?vidId=SCDlAp8Yxik' />"+
    "<param name='allowFullScreen' value='true' />"+
    "<param name='allowscriptaccess' value='always' />"+
    "<embed src='Js/YTPlayer.swf?vidId=SCDlAp8Yxik' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='425' height='344'></embed>"+
    "</object>"+
    "<br />"+
    "<p>If you cannot view this video <a href='#' onClick='changeVideo(5);'>Click Here</a></p>";
  }
  
  return videoData;
}

function changeVideo(num)
{
  var videoData = getAltVideo(num);
  
  $("#modal_window").empty();
  $("#modal_window").html(videoData);
}
function showchangeCertOwnerShip(event)
{
  var ButtonHandle=$(event.target);
  ButtonHandle.hide();
  ButtonHandle.siblings("div").fadeIn();
}
function changeCertOwnerShip(event)
{
  var ButtonHandle=$(event.target);
  ButtonHandle.parent("div").hide();
  ButtonHandle.parent("div").siblings("input").fadeIn();
  var nameChangeValue=ButtonHandle.siblings("input[name='cert_name_change_text']").attr("value");
  var nameChangecredit_id=ButtonHandle.siblings("input[name='credit_id']").attr("value");
$.getJSON(globalPagePath+"index.php",{'section':'user','AJAXaction':'change_cert_name','credit_id':nameChangecredit_id,'newname':nameChangeValue},
  function(data)
  {
    if(data.status==true)
    {
      alert("Name change Successful");
      window.location=window.location;
    }
    if(data.status==false)
    {
      alert("Name change failed."+data.content);
    }
  });
}
function showPointsTransfere(event)
{
  var accountid=event.target.id;
  accountid=accountid.substr(11,accountid.length);
  var LinkRef=globalPagePath+"index.php?section=user&AJAXaction=view_points_transfere_form&account_id="+accountid;
  $.get(LinkRef,
  function(data)
  {
    if(data!="")
    {
      show_modal_page(data,450,475);
      $("#transfere_points").submit(function()
      {
        if(GeneralRuleValidation())
        {
          return true; 
        }
        return false;
      });

    }
    else
    {
      show_modal_page("<P>Page not found, Please contact your Support Administrator</P>",344,425);
    }
  });
}

