//////////////////////////////////////////////////////////////////////////////////////
//XML HTTP functions to retrieve parts of the page
//////////////////////////////////////////////////////////////////////////////////////
function GetXmlHttpObject()
  {
   var xmlHttp = null;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      try
        {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      catch (e)
        {
          return null;
        }
      }
    }
    return xmlHttp;
  }

var request = new Array(7); 
function RequestData(url, id, index)
{
  attachEvents();
  request[index] = GetXmlHttpObject();
  var indexOfHash = url.indexOf('#',0);
  var targetElement = null;
  if (indexOfHash > 0)
  {
    targetElement = url.substring(indexOfHash);
    url = url.substring(0,indexOfHash);
  }
  if (request[index])
  {
    request[index].onreadystatechange = function ()
      {
        if(request[index].readyState==4)
        {
          document.getElementById(id).innerHTML = request[index].responseText;
          request[index] = null;
          detachEvents();
          if (targetElement)
          {
            //Focusing on an element did not work for IE6
            document.location.href = targetElement;
          }
        }
      };
    request[index].open("GET",url,true);
    request[index].send(null);
  }
}
//////////////////////////////////////////////////////////////////////////////////////
//Switching between English and Arabic
//////////////////////////////////////////////////////////////////////////////////////
var equivalentPage = "./Arabic/Home_arabic.html";
var switchLanguage = "arabic";
m1.rev=0;
m1.v22=0;
function SwitchView()
{
  if (switchLanguage == "english")
  {
    document.getElementById("MainTable").style.direction = "ltr";
    window.document.title = "NEDA - National Egyptian Development Association";
    document.getElementById("LanguageImage").innerHTML = "<br><IMG src='./Images/a1.gif' onmouseover=\"this.src='./Images/a1.gif'\" onmouseout=\"/*this.src='./Images/a2.gif'*/\"  border='0'><br>";
    RequestData("./English/Left Menu.html","LeftMenu",1);
    RequestData(equivalentPage,"Content",2);
    RequestData('./English/advert.html','Advertising',3);
    RequestData('./English/Footer.html','Footer',4);
    equivalentPage = equivalentPage.replace('.html', '_arabic.html');
    equivalentPage = equivalentPage.replace('English', 'Arabic');
    switchLanguage = "arabic";
    m1.rev=0;
    m1.v22=0;
    m1.lev0[0]="13px";
    m1.lev1[0]="13px";
    m1.className = "";
  }
  else if (switchLanguage == "arabic")
  {
    document.getElementById("MainTable").style.direction = "rtl";
    window.document.title = "المؤسسة الوطنية المصرية للتنمية - ندا";
    document.getElementById("LanguageImage").innerHTML = "<br><IMG src='./Images/e2.gif' onmouseover=\"this.src='./Images/e2.gif'\" onmouseout=\"/*this.src='./Images/e1.gif'*/\" border='0'><br>";
    RequestData("./Arabic/Left Menu_arabic.html","LeftMenu",1);
    RequestData(equivalentPage,"Content",2);
    RequestData("./Arabic/advert_arabic.html","Advertising",3);
    RequestData('./Arabic/footer_arabic.html','Footer',4);
    equivalentPage = equivalentPage.replace('_arabic', '');
    equivalentPage = equivalentPage.replace('Arabic', 'English');
    switchLanguage = "english";
    m1.rev=1;
    m1.v22=2;
    m1.lev0[0]="";
    m1.lev1[0]="";
    m1.className = "arabic";
    
  }
} 
//Opens pages that only exist in Arabic
function OpenArabicOnlyPage(pagePath)
{
  if (switchLanguage == "arabic")
  {
    document.getElementById("MainTable").style.direction = "rtl";
    window.document.title = "المؤسسة الوطنية المصرية للتنمية - ندا";
    document.getElementById("LanguageImage").innerHTML = "<br><IMG src='./Images/e2.gif' onmouseover=\"this.src='./Images/e2.gif'\" onmouseout=\"/*this.src='./Images/e1.gif'*/\" border='0'><br>";
    RequestData("./Arabic/Left Menu_arabic.html","LeftMenu",1);
    RequestData(pagePath,"Content",2);
    RequestData("./Arabic/advert_arabic.html","Advertising",3);
    RequestData('./Arabic/footer_arabic.html','Footer',4);
    equivalentPage = equivalentPage.replace('_arabic', '');
    equivalentPage = equivalentPage.replace('Arabic', 'English');
    switchLanguage = "english";
    m1.rev=1;
    m1.v22=2;
    m1.lev0[0]="";
    m1.lev1[0]="";
    m1.className = "arabic";
  }
  else
  {
    RequestData(pagePath,"Content",2);
  }
}
//////////////////////////////////////////////////////////////////////////////////////
//Application form scripts
//////////////////////////////////////////////////////////////////////////////////////
function OpenApplicationForm()
{
  OpenArabicOnlyPage("./Arabic/TermsAndConditions_arabic.html");
}

//Loads the days depending on month and year selected
function LoadDays(year,month, days)
{
  if (year == '' || month == '')
  {
    days.innerHTML = '';
    days.options.add(new Option('إختر السنة و الشهر أولا', ''));
    days.style.width = '150px';
    return false;
  }
  var currentLength = days.options.length;
  var leapYear = false;
  if (year%4 == 0){ leapYear = true; }
  var supposedLength = 31;
  if (leapYear && month == '02'){ supposedLength = 29; }
  if ((!leapYear) && month == '02'){ supposedLength = 28; }
  if (month=='04' || month=='06' || month=='09' || month=='11'){ supposedLength = 30; }
  if (currentLength != supposedLength){ GenerateOptions(days, supposedLength); }
}
//Generates options in the given days element for count times
function GenerateOptions(days, count)
{
  currentIndex = days.selectedIndex;
  days.innerHTML = '';
  for (i=1; i<=count; i++)
  {
    days.options.add(new Option(i, ((i<10)?'0':'')+i));
  }
  days.selectedIndex = (currentIndex<days.options.length)?currentIndex:0;
  days.style.width = "50px";
}
//Enables/Disables a control/set of controls based on a base value
function EnableNextControl(currentValue, controls, valueToCompare)
{
  if (controls.length)//if controls is an array of inputs
  {
    for (i=0; i<controls.length; i++)
    {
      controls.disabled = (currentValue != valueToCompare);
    }  
  }
  else//controls is only one input
  {
    controls.disabled = (currentValue != valueToCompare);
  }
}
//////////////////////////////////////////////////////////////////////////////////////
//XML HTTP functions to submit a form
//////////////////////////////////////////////////////////////////////////////////////
function submitForm(form, url, index, handler, handlerParameters)
{
  if (!index)
  {
    index = 0;
  }
  if (request[index]) return false;
  var postData = GetParameters(form);
  attachEvents();
  request[index] = GetXmlHttpObject();
  if (request[index])
  {
    request[index].onreadystatechange = function (){
        if(request[index].readyState==4)
        {
          if (handler)
          {
            InvokeHandler(handler, request[index], handlerParameters);
          }
          else
          {
            document.body.innerHTML = request[index].responseText;
          }
          request[index] = null;
          detachEvents();
        }
      };
    if (form.method.toLowerCase() == "post")
    {
      request[index].open("POST",url,true);            
      request[index].setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
      request[index].send(postData);
    }
    else if (form.method.toLowerCase() == "get")
    {
      request[index].open("GET",url+"?"+postData,true);
      request[index].send(null);
    }
  }
}

function GetParameters(form)
{
  var postString = "";
  for (i=0;i<form.length;i++)
  {
    if (form.elements[i].tagName.toLowerCase() == "input")
      postString += form.elements[i].name+"="+form.elements[i].value+"&";
    if (form.elements[i].tagName.toLowerCase() == "select")
      postString += form.elements[i].name+"="+form.elements[i].value+"&";
    if (form.elements[i].tagName.toLowerCase() == "textarea")
      postString += form.elements[i].name+"="+form.elements[i].value+"&";
  }
  return postString.substring(0,postString.length-1).replace(/\s/g, "%20").replace(/\+/g, "%2B");
}

function disableEvent()
{
  event.cancelBubble = true;
  event.returnValue = false;
  return false;
}

//I got this function from http://www.scottandrew.com/weblog/articles/cbs-events
function addEvent(element, eventType, functionToAttach, useCapture){
  if (element.addEventListener){
    element.addEventListener(eventType, functionToAttach, useCapture);
    return true;
  } else if (element.attachEvent){
    var r = element.attachEvent("on"+eventType, functionToAttach);
    return r;
  } else {
    return false;
  }
}

function removeEvent(element, eventType, functionToDetach, useCapture){
  if (element.removeEventListener){
    element.removeEventListener(eventType, functionToDetach, useCapture);
    return true;
  } else if (element.detachEvent){
    var r = element.detachEvent("on"+eventType, functionToDetach);
    return r;
  } else {
    return false;
  }
}

function attachEvents()
{
  addEvent(window.document.body, "click", disableEvent, false);
  addEvent(window.document.body, "keyup", disableEvent, false);
  window.document.body.style.cursor = "wait";
  /*if (!window.document.getElementById("loading"))
  {
    window.document.body.innerHTML+=loading;
  }
  window.document.getElementById("loading").style.display = "block";*/
}

function detachEvents()
{
  removeEvent(window.document.body, "click", disableEvent, false);
  removeEvent(window.document.body, "keyup", disableEvent, false);
  window.document.body.style.cursor = "auto";
  /*if (!document.getElementById("loading"))
  {
    window.document.body.innerHTML+=loading;
  }
  window.document.getElementById("loading").style.display = "none";*/
}

function InvokeHandler(handler, ajaxResponse, handlerParameters)
{
  handler(ajaxResponse, handlerParameters);
}

function applyOnlineHandler(response, parameters)
{
  if (response.responseText == "1") 
  {
    //alert("تم إرسال الإستمارة بنجاح");
    document.getElementById(parameters[0]).innerHTML = parameters[1];
  }
  else
  {
    //alert("لم يتم إرسال الإستمارة. رجاء المحاولة مرة أخرى.");
    document.getElementById(parameters[0]).innerHTML = parameters[2];
  }
  response = null;
  window.document.body.style.cursor = "auto";
  return null;
}
//////////////////////////////////////////////////////////////////////////////////////
//Online Tests
//////////////////////////////////////////////////////////////////////////////////////
function CalculateScore()
{
  var totalScore = 0;
  for (i=0; i<280; i++)
  {
    if (document.forms[0].elements[i].checked)
      totalScore += parseInt(document.forms[0].elements[i].value);
  }
  var alertText = 'لقد حصلت على '+totalScore+' درجة و هذا يدل على:\r\n';
  if (totalScore >= 275)
    alertText += 'إنك فعلاً شديد الثقة بنفسك و قادر على معرفة نفسك حق المعرفة';
  if (totalScore >= 250 && totalScore < 275)
    alertText += 'إنك شخص واثق من نفسك بعض الشئ و قادر على إكتساب المزيد من الثقة بالنفس و تستطيع أن تعرف نفسك بقدر معقول';
  if (totalScore < 250)
    alertText += 'إنك تحتاج إلى مزيد من الجهد لإكتساب الثقة بالنفس ‘ و تحتاج المزيد من الجهد الفائق كى تعرف نفسك جيداً';
  alert(alertText);
}
//////////////////////////////////////////////////////////////////////////////////////
//Google Analytics
//////////////////////////////////////////////////////////////////////////////////////
function TrackPage()
{
  try {
  var pageTracker = _gat._getTracker("UA-10771703-1");
  pageTracker._trackPageview();
  } catch(err) {}
}