
// This file contains all general JS functions
// Copyright Babysoft


// Get all data, no matter what type of data and return them out as a hidden
// input values. This will includes all inputs, text field, checkbox value
// dropdown list and radio button
// Param1: null
// Return: return an array of string. index 0 is all the value are seperated 
//         into the input=hidden format. The name of the value is the id/name
//         of the original field. index 1 is the get version of all the value
//         without the ?, the form will be something like: 
//         name1=value1&name2=value2...
// In input field, we do not handle type: image, file
function dataget(){
    var temp;
    var post = '';
    var get = '';
    var ary = new Array();

    // This is for Input Tag //
    var inputobj = document.getElementsByTagName('input');
    for (var i=0; i < inputobj.length; i++){
      if (inputobj[i] != null){

	// All input tag except image and file
	if (inputobj[i].type == 'text' || inputobj[i].type == 'hidden' || inputobj[i].type == 'password' || 
	    inputobj[i].type == 'button' || inputobj[i].type == 'reset' || inputobj[i].type == 'submit' ||
	    (inputobj[i].type == 'radio' && inputobj[i].checked == true) || 
	    (inputobj[i].type == 'checkbox' && inputobj[i].checked == true) ){
	  if (inputobj[i].name == undefined || inputobj[i].name == null || inputobj[i].name == ''){
	    post += '<input type=hidden name="'+inputobj[i].id+'" value="'+inputobj[i].value+'">';
	    if (get==''){get+=inputobj[i].id+'='+inputobj[i].value;}else{get+='&'+inputobj[i].id+'='+inputobj[i].value;}
	  }else{
	    post += '<input type=hidden name="'+inputobj[i].name+'" value="'+inputobj[i].value+'">';
	    if (get==''){get+=inputobj[i].name+'='+inputobj[i].value;}else{get+='&'+inputobj[i].name+'='+inputobj[i].value;}
	  }
	}
      }
    }

    // This is for text area //
    inputobj = document.getElementsByTagName('textarea');
    for (var i=0; i < inputobj.length; i++){
      if (inputobj[i] != null && inputobj[i].value != null){
	if (inputobj[i].name == undefined || inputobj[i].name == null || inputobj[i].name == ''){
	  post += '<input type=hidden name="'+inputobj[i].id+'" value="'+inputobj[i].value+'">';
	  if (get==''){get+=inputobj[i].id+'='+inputobj[i].value;}else{get+='&'+inputobj[i].id+'='+inputobj[i].value;}
	}else{
	  post += '<input type=hidden name="'+inputobj[i].name+'" value="'+inputobj[i].value+'">';
	  if (get==''){get+=inputobj[i].name+'='+inputobj[i].value;}else{get+='&'+inputobj[i].name+'='+inputobj[i].value;}
	}
      }
    }

    // This is for Select / Option Field //
    inputobj = document.getElementsByTagName('select');
    for (var i=0; i < inputobj.length; i++){
      if (inputobj[i] != null && inputobj[i].options != null && inputobj[i].selectedIndex != null){
        temp = inputobj[i].options[inputobj[i].selectedIndex].value;
	if (inputobj[i].name == undefined || inputobj[i].name == null || inputobj[i].name == ''){
	  post += '<input type=hidden name="'+inputobj[i].id+'" value="'+temp+'">';
	  if (get==''){get+=inputobj[i].id+'='+temp;}else{get+='&'+inputobj[i].id+'='+temp;}
	}else{
	  post += '<input type=hidden name="'+inputobj[i].name+'" value="'+temp+'">';
	  if (get==''){get+=inputobj[i].name+'='+temp;}else{get+='&'+inputobj[i].name+'='+temp;}
	}
      }
    }

    // GET URL do not allow space, replace it with +
    get = get.replace(/ /g,'+');

    ary[0] = post;
    ary[1] = get;

    return ary;
}




// Display the Popup Screen (with the post submit form)
// Param1: The submit Action Flag
// Param2: The width of the screen
// Param3: The height of the screen
// Param4: (Opt.) Additional hidden value you wish to pass to the server
// Param5: (Opt.) If you want to use an existing window object, use it here.
// Return: the new window object
function myPopup(submitAction, width, height, value, newWin){

  var uname = '';
  var ssid = '';
  var myWidth = 0;
  var myHeight = 0;

  if (submitAction == null || submitAction == ''){
    submitAction = "";
  }

  if (width == null || width == ''){
    width = 800;
  }

  if (height == null || height == ''){
    width = 600
  }

  if (value == undefined || value == null){
    value = '';
  }

  if (document.getElementById('uname') != null){
    uname = document.getElementById('uname').value;
  }

  if (document.getElementById('ssid') != null){
    ssid = document.getElementById('ssid').value;
  }

  if (newWin == null || newWin == undefined || newWin == ''){
    newWin = window.open('','','left=120,top=120,width='+width+',height='+height+',toolbar=no,resizable=yes,location=no,directories=no,status=no,menubar=no,scrollbars=yes');
  }else{
    // Scroll Down Screen
    /* while (myWidth < (width - newWin.innerWidth) || myHeight < (height - newWin.innerHeight)){
      if (myWidth < (width - newWin.innerWidth)){
        myWidth = myWidth + 0.3;
      }
      if (myHeight < (height - newWin.innerHeight)){
        myHeight = myHeight + 0.2;
      }
      newWin.resizeBy(myWidth, myHeight);
    }*/
    newWin.resizeBy(width - newWin.innerWidth, height - newWin.innerHeight);
  }

  newWin.document.writeln('<center><br><br>Please wait for system loading<br><br></center>');
  newWin.document.writeln('<center><img src="./others/images/myloading2.gif"></center>');
  newWin.document.writeln('<form id="hiddenForm" method="post" action="">');
  newWin.document.writeln('<input type=hidden name="submitAction" value="'+submitAction+'" />');
  newWin.document.writeln('<input type=hidden name="uname" value="'+uname+'" />');
  newWin.document.writeln('<input type=hidden name="ssid" value="'+ssid+'" />');
  newWin.document.writeln(value);
  newWin.document.writeln('</form>');

  newWin.document.getElementById("hiddenForm").submit();
  newWin.focus();

  return newWin;

}



// Get the client machine date and time and get ready it
// for backend storage use
// Param1: The major submit data container (eg. submitFlag)
// Return: date data in GET format
function setMachineDate(submitFlag){

  // Assign Client Machine Date and Time
  var mydate = new Date();
  var cdate = 'ClientMachineDate';
  var ctime = 'ClientMachineTime';
  var czone = 'ClientMachineZone';
  // var offset = mydate.getTimezoneOffset() / 60; // This is offset in hours
  var offset = mydate.getTimezoneOffset();
  var getformat = '';
  var getdate = mydate.getFullYear() + '-' + chkDigitSize((mydate.getMonth() + 1),2) + '-' + chkDigitSize(mydate.getDate(),2);
  var gettime = chkDigitSize(mydate.getHours(),2) + ':' + chkDigitSize(mydate.getMinutes(),2) + ':' + chkDigitSize(mydate.getSeconds(),2);

  if (submitFlag !== false && document.getElementById(submitFlag) != null){
    document.getElementById(submitFlag).innerHTML += '<input type=hidden id='+cdate+' name='+cdate+' value="'+ getdate + '">';
    document.getElementById(submitFlag).innerHTML += '<input type=hidden id='+ctime+' name='+ctime+' value="'+ gettime + '">';
    document.getElementById(submitFlag).innerHTML += '<input type=hidden id='+czone+' name='+czone+' value="'+ offset + '">';
  }

  getformat = cdate + '=' + getdate + '&' + ctime + '=' + gettime + '&' + czone + '=' + offset;

  return getformat;

}


// Restore the data from the Delimitator (Field / Value) Seperation to an associative array
// This function expect the result from template_passdata (type=1) returned value
// Param1: Data formatted in Delimitator (Field / Value) Seperation
// Param2: Type of data format, default [0/null/empty]: is Delimitator (Field/Value) format
// Return: an associative array with the field / value pair
function data2hash(data, type){
  
  var hash = new Array();
  var temp = new Array();
  var tempi = new Array();
  var size = 0;

  if (data == null || data == ''){
    return;
  }

  if (type == null || type == 0 || type == ''){
    temp = data.split(FIELD_DELIMITATOR);
    size = temp.length;
    for (i=0; i < size; i++){
      tempi = temp[i].split(VALUE_DELIMITATOR);
      tempi[0] = tempi[0].replace(/\s/g,'');
      // alert('(' + tempi[0] + ')-(' + tempi[1] + ')');
      if (tempi[1] == undefined || tempi[1] == null){
        hash[tempi[0]] = '';
      }else{
        hash[tempi[0]] = tempi[1];
      }
    }
  }

  return hash;

}



// Create a get/post data format based on the pass in hash
// Param1: (Req.) The hash required to convert into data passing format
// Param2: (Opt.) The format you wish to use. 
//                         Empty/null/0 (default): post hidden format, 1:Get format
// Return: The a string for data pass form based on parameters
function hash2data(hash, type){

  var output = '';
 
  if (type == null || type == '' || type == '0'){
    type = '0';
  }

  for (var key in hash){
    // post hidden format
    if (type == '0'){
      output += '<input type=hidden name="'+key+'" id="'+key+'" value="'+hash[key]+'">' + "\n";
    }
    // get format
    else if (type == '1'){
      if (output == ''){
        output += key+'='+hash[key];
      }else{
        output += '&'+key+'='+hash[key];
      }
    }
  }
  return output;
}





// Check is the id value contains new line character or not (\n). 
// It will return true if \n exist 
// And clean up the \n character in the value
// Param1: (Req.) the id you wish to check
// Return: true if the value contains \n, otherwise false
function isEnter(id){

  if (id == '' || document.getElementById(id) == null){
    return false;
  }

  var value = document.getElementById(id).value;

  if (value.indexOf("\n") != -1 || value.indexOf("\r") != -1){
    value = value.replace(/\n/g,'');
    value = value.replace(/\r/g,'');
    document.getElementById(id).value = value;
    return true;
  }else{
    return false;
  }


}


// The help function for mySleep
function mySleep_help(now, count){

  if (now >= count){
    return;
  }else{
    now = now + 1;
  }
  setTimeout("mySleep_help("+ now +"," + count + ");",1000);

}


// Sleep n seconds and get up again
// Param1: (Opt.) How Long (in seconds) you wish to sleep (default 1)
// Return: false always
function mySleep(seconds){

  if (seconds == null || seconds == undefined || seconds == ''){
    seconds = 1;
  }else{
    seconds = seconds;
  }

  mySleep_help(0, seconds);

  return false;

}


// Show the content of the array, no matter it Hash or Regular Array
// Param1: The array you wish to show
// Param2: Display Method: 0/null/empty: same window, 1: alert, 2: new window
// Return: false always
function showarray(array, win){

  var output = "array[] => <br>\n";
  for (var key in array){
      output += "     ["+key+"] => (" + array[key]+")" + "<br>\n";
  }
  output += "<br>\n";


  if (win == null || win == undefined || win == ''){
    document.writeln(output);
  }else if (win == '1'){
    alert();
  }else if (win == '2'){
    newWin = window.open('','showarray');
    newWin.document.writeln(output);
  }

  return false;

}


// Convert / Restore Special Characters
// This function will convert / restore special characters into available words
// Or restore it back into original state
// Param1: (Req.) The full string you wish to convert / restore
// Param2: (Opt.) flag indicate what you wish to do. False (default): convert, True: restore
// Return: a converted / restored string
function convertSpecialChar(data, flag){

  // Handling: ' " & + \

  // Convert the invalid characters into special data
  if (flag == undefined || flag == null || flag === false || flag == ''){
    data = data.replace(/\'/g,SPECIAL_CHAR_MYQUOTE);
    data = data.replace(/\"/g,SPECIAL_CHAR_MYDQUOTE);
    data = data.replace(/\&/g,SPECIAL_CHAR_MYAND);
    data = data.replace(/\+/g,SPECIAL_CHAR_MYPLUS);
    data = data.replace(/\\/g,SPECIAL_CHAR_MYSLASH);
  }
  // Restore back to the original data
  else{
    data = data.replace(RegExp(SPECIAL_CHAR_MYQUOTE,"g"),"\'");
    data = data.replace(RegExp(SPECIAL_CHAR_MYDQUOTE,"g"),"\"");
    data = data.replace(RegExp(SPECIAL_CHAR_MYAND,"g"),"\&");
    data = data.replace(RegExp(SPECIAL_CHAR_MYPLUS,"g"),"\+");
    data = data.replace(RegExp(SPECIAL_CHAR_MYSLASH,"g"),"\\");
  }
  return data;
}



// Display / Hidden a table
// Param1: (Req.) The table id you wish to display / hide
// Param2: (Opt.) action you wish to perform. False (default): hide, True: display
// Return: false always;
function showhidden(id, flag){

  if (flag == undefined || flag == null || flag === false || flag == ''){
    flag = false;
  }else{
    flag = true;
  }

  if (id == null || id == '' || document.getElementById(id) == null){
    alert('mylib->showhidden: id ('+id+') not found, please check it and try again.');
    return false;
  }

  if (flag === true){
    document.getElementById(id).style.visibility='visible';
  }else{
    document.getElementById(id).style.visibility='hidden';
  }
  return false;
}


// Submit a page change "Action Alert" to the server. 
// Return: false always
function startSessionTrack(){
  var url = location.href;
  var submitAction = '__base_mylogin_setActionAlert__';
  var alldata = new Array();
  var response = null;

  // Now, form is ready, use the form to submit
  alldata = dataget();
  alldata[1] += '&submitAction=' + submitAction;
  // ajax_go(url, alldata[1], true);
  response = ajax_go(url, alldata[1], false);
  // alert(response);
  return false;

}


// Separate the URL and the Query portion (all # and ? will be removed)
// Param1: (Opt.) The URL (with query) you wish to remove
// Return: an array separated URL & Query (index 0: URL, 1+ is the queries)
function splitURLQuery(url){
  var temp = '';
  var tempAry = new Array();

  if (url == undefined || url == null || url == ''){
    temp = location.href.replace(/\#/g,'');
  }else{
    temp = url.replace(/\#/g,'');
  }
  tempAry = temp.split('?');

  return tempAry;

}



// Sort an associative array (even number index works)
// Param1: (Req.) The array you wish to sort
// Return: a sorted array, with the original key index
function mySort(ary){

  var delim = '-----WOOWWOWOWOWOAsDFSADFBABYSOFTaSDFSADFWOWOW-';
  var myary = new Array();
  var finish = new Array();
  var index = size = 0;
  var tempary = new Array();

  // Specially handle the index //
  for (key in ary){
    myary[index] = ary[key] + delim + key;
    index++;
  }
  myary = myary.sort();
  size = myary.length;
  for (var i=0; i < size; i++){
    // alert(myary[i]);
    tempary = myary[i].split(delim);
    finish[tempary[1]] = tempary[0];
  }

  // testing //
  // for (key in finish){alert(key + '-' + finish[key]);}

  return finish;

}

