/*
 * This JS file for game module
 **/

// on load this will be triggered
$(document).ready(function() {

	//$(".accordion h3:first").addClass("active");
  // show all the options, they might now know that its an accordion
	//$(".accordion p:not(:first)").hide();

  $(".accordion p").hide(); // hides all accordion

  $(".accordion h3").click(function(){
      $(this).next("p").slideToggle("fast")
      .siblings("p:visible").slideUp("fast");
      $(this).toggleClass("active");
      $(this).siblings("h3").removeClass("active");
  });


  $("#lstRegion").change(bindZone);

  bindZone(); // pre-populate the server dropdown
  
  // attach the radio button click
  $("input[name='package_id']").click( function() {

      var package_id = $(this).val();

      //alert(package_id);

      if (package_id == 0) {
          $('#amount').html("$ 0");
          $('input#power-amount').val(0);
          updateTotalPrice();
      } else {

        $.ajax({
         type: "POST",
         url: base_url +"game/getpackage/"+package_id,
         success: function(data) {
          $('#amount').html("$ " + data);
          $('input#power-amount').val(data);
          updateTotalPrice();
         }
        });

      } // end if
      
  }); // end select by radio box

  /*
  // attach the checkbox click
  $("input[name='chkAdd']").click( function() {

      if (this.checked) {

        $(this).siblings('select').removeAttr('disabled');
        
        var select = $(this).siblings("select[@selected]");

        var value = select.val();
        var price = select.find('option[value="' + value + '"]').attr('rel');

        $(this).siblings('input[type="hidden"]').val(price);
        $(this).siblings('span.price').html("$ " + price);

      } else {

        $(this).siblings('select').attr('disabled', 'disabled');
        $(this).siblings('input[type="hidden"]').val("0");
        $(this).siblings('span.price').html("");
      }

      updateAddonsPrice();
      
  }); // end select by check box

  */

 
  $("select").change( function() {

    var value = $(this).val();
    var price = $(this).find('option[value="' + value + '"]').attr('rel');

    $(this).siblings('input[type="hidden"]').val(price);
    $(this).siblings('span.price').html("$ " + price);

    updateAddonsPrice();

  });

});


/* This js is will be using on the selection of zone and faction*/


function updateAddonsPrice() {

  // lets loop thru the hidden fields
  var total = 0;
  $('input.addon-price').each( function (i, selected) {
    
    total = total + parseFloat($(selected).val());
  });

  $('input#addons-total-price').val(total);
  $('span.addons_amount').html("Total Addons : $ " + total);

  updateTotalPrice();

} // end updateAddonsPrice

function updateTotalPrice() {
  var total = parseFloat($('input#addons-total-price').val());
  total = total + parseFloat($("input#power-amount").val());
  total = total.toFixed(2)

  $('#total-amount').html(total);
  $('input#total-amount2').val(total);

} // updateTotalPrice



function bindZone() {
	//disable child select list
	$("#lstServer").attr("disabled", true);
 
 	//game name
	var gn = $("#gamename").val();
	//querystring value is selected value of parent drop down list
	var qs = $("#lstRegion").val();
	
	//if user selected a separator, show error
	if((qs == '') || (qs == undefined)) {
      $('#lstServer').attr('disabled', 'disabled');
      $('#lstServer').empty();
      $('#lstServer').append($("<option value=''>-- Select Server --</option>"));
	}
	else {
		//show message indicating we're getting new values

        $.ajax({
         type: "POST",
         url: base_url +"game/zone/"+qs,
         dataType: "json",
         success: function(data) {
           $('#lstServer').removeAttr('disabled');
           $('#lstServer').empty();
           $.each(data, function() {
              $('#lstServer').append($("<option value='" + this.value + "'>" + this.name + "</option>"));
           });
         }
        });
	} // end if
} // end function


function powerLevel(){
	
	var gameid = $("#game-id").val();
	var level = $("#your-level").val();	//your level	
	var desire = $("#desire-level").val();//desired level

  if (validatePowerLeveling()) {

    $.ajax({
      type: "POST",
      url: base_url +"game/calculate/"+gameid+"/"+level+"/"+desire,
      success: function(data) {
        $('#amount').html("$ " + data);
        $('input#power-amount').val(data);
        updateTotalPrice();
      }
    });   
  } // end if

  if (validatePowerLeveling()) {
    $.ajax({
      type: "POST",
      url: base_url +"game/gettime/"+gameid+"/"+level+"/"+desire,
      success: function(data) {
        $('#time').html(data);
        $('input#estimated-time').val(data);
      }
    });

  } // end if
} // end powerlevel


function showDialog(title, msg) {

  $("#game-dialog").attr('title', title);
  $("#game-dialog-msg").html(msg);

  $("#game-dialog").dialog({
			bgiframe: true,
			modal: true,
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
		});
  $("#game-dialog").dialog('open');
}

function validatePowerLeveling() {
  // get the fields
  var current_level = jQuery.trim($('#your-level').val());
  var desired_level = jQuery.trim($('#desire-level').val());

  // check if both have values
  if (current_level != '' && desired_level != '') {

    // lets check if the values are numeric
    var result1 = /^\d+$/i.test(current_level);
    var result2 = /^\d+$/i.test(desired_level);
	var maxlevel = eval($("#max-level").val());//max level

    var msg = "";
    if (!result1) msg = msg + "'Your Level' must be in numeric format.<br/>";
    if (!result2) msg = msg + "'Desired Level' must be in numeric format.<br/>";
	if(desired_level > maxlevel) msg = msg + "'Desired Level' not be more than "+maxlevel+" maximum level";

    if (msg != "") {
      showDialog('Error!', msg);
      return false;
    } else {
      return true;
    }


  } else {
    showDialog('Error!', "Fields 'Your Level' and 'Desired Level' are required!");
    return false;
  }

  return false;
} // validatePowerLeveling

function validateOptions() {

  // get fields
  var region = $('#lstRegion').val();
  var server = $('#lstServer').val();
  var faction = $('#lstFaction').val();

  // check the faction server
  var last_faction_value = $("#lstFaction:last-child").val();

  var msg = "";

  if (region == "") msg = msg + "Please select a Region<br/>";
  if (server == "") msg = msg + "Please select a Server<br/>";
  if (faction == "" && last_faction_value != "") msg = msg + "Please select a Faction<br/>";

  if (msg != "") {
    showDialog('Error!', msg);
    return false;
  }

  return true;

} // end validateOptions


function validateAccountNameAndCharacterName() {

  // get fields
  var account_name = $('#account_name').val();
  var character_name = $('#character_name').val();

  var msg = "";

  if (account_name == "") msg = msg + "Account Name is required<br/>";
  if (character_name == "") msg = msg + "Character Name is required<br/>";

  if (msg != "") {
    showDialog('Error!', msg);
    return false;
  }

  return true;

} // end validateOptions



function validatePowerAmount() {

  var value = parseFloat($('#power-amount').val());
  var total = parseFloat($('#total-amount2').val());
  
  var current_level = jQuery.trim($('#your-level').val());
  var desired_level = jQuery.trim($('#desire-level').val());

  var result = true;
    
  if (current_level!='' || desired_level!='') {
    result = validatePowerLeveling();    
  }
  
    
  if (value==0 && total==0) {
      showDialog('Error!', "Please pick your desired Power Leveling Package or Create a Custom Package and click Calculate to get the amount of your Custom Package and/or select an Add-on.");
      return false;
  }
  
  return true;

} // end validatePowerAmount

function validateAndSubmit() {

  // get the fields
  //var result = validatePowerLeveling();
  var result = validatePowerAmount();
  if (result) result = validateAccountNameAndCharacterName();
  if (result) result = validateOptions();

  if (result) {
    // everything is valid
    // proceed with submit
    $('#game-addcart').submit();

    //return true;
  } // end if

  return false;
}