/**
 * Oskar Mobil a.s. - Web Self Care EcmaScript Main Library
 * @version $Id: main.js 1205 2009-09-11 11:43:06Z xsartiwa $
 */

/* list of all startup actions in EcmaScript */
function startActions(){
  resContent();
  hypAndForm();
  target2forms();
  prepareBoxOverData();
  boxoverInit();
}

function beforeLeave(anchor){
  if (!bfLeaveMsg) window.location.href=anchor.href;
  var leave = confirmOption(anchor, '', bfLeaveMsg, '300', bfLeaveYes, 'logout.php?type=external&amp;go='+anchor.href, bfLeaveNo, '');
  return false;
}

function target2forms(){
  var searchForm = document.getElementById('searchFormExt1');
  if (searchForm)
    searchForm.target = '_blank';
}

function boxoverInit() {
  init();
  if (typeof document.attachEvent!='undefined') {
     document.attachEvent('onmousemove',moveMouse);
     document.attachEvent('onclick',checkMove); }
  else {
     document.addEventListener('mousemove',moveMouse,false);
     document.addEventListener('click',checkMove,false);
  }
}

function prepareBoxOverData() {
 if (!document.getElementsByTagName) return;
 prepareBoxOverData2( document.getElementsByTagName("a") );
 prepareBoxOverData2( document.getElementsByTagName("span") );
 prepareBoxOverData2( document.getElementsByTagName("td") );
}

function prepareBoxOverData2(nodes) {
 var i, j, x, y, z;
 for (i=0; i < nodes.length; i++) {
   x = nodes[i];
   z = ""+x.getAttribute("title");
   if(z.length > 30) {
     j = (x.hasChildNodes()) ? x.firstChild.data : "";
     j = (typeof(j) != 'undefined' && j.length) ? j : "&#160;";
     if (x.title.indexOf("header=[") == -1)
       x.title = "header=["+j+"] body=["+z+"]";
   }
 }
}

function showAndHide(id){
  box = document.getElementById(id);
  box.style.display = (box.style.display!='none') ? 'none': 'block';
}

function showAndHideElementsByName(name,show){ //arg[2] = element id, //arg[3] = text when hide, //arg[4] = text when show
  elements = document.getElementsByName(name);
  //IE
  if(!elements.length){
    elements = Array();
    tags = document.getElementsByTagName('*');
    for(var i in tags){
      if(tags[i].name == name) elements[elements.length] = tags[i];
    }
  }
  for(var i in elements){
    if(elements[i].style) elements[i].style.display = (show) ? 'block': 'none';
  }
  if(arguments[2]){
    document.getElementById(arguments[2]).innerHTML = (show) ? arguments[4]: arguments[3];
  }
}

function showAndHideButton(o,b){ //atr[0] => show/hide id object //atr[0] => plus/minus id button
 var element = document.getElementById(o);
  var butt = document.getElementById(b);
  if(element.style.display == "none") {
     element.style.display = "block";
     butt.className = "btnMinus";
  }
  else {
    element.style.display = "none";
    butt.className = "btnPlus";
  }
}

function hypAndForm(){
  var i;
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("rel") == "external") {
     anchor.target = "_blank";
   } else {
/*
     if (!anchor.getAttribute("onclick") && (anchor.href.indexOf('javascript:')!=0)){
        anchor.onclick = doLockAll;
     }
*/
   }
 }
 var forms = document.getElementsByTagName("form");
 for (i=0; i<forms.length; i++) {
   var frm = forms[i];
   if (frm.getAttribute("rel") == "external") {
     frm.target = "_blank";
   } else {
/*
     var action = '';
     for(var s=frm.attributes.length; s>0;s--)
       if(frm.attributes[s-1].nodeName=='action')
         action = frm.attributes[s-1].nodeValue;
     if(!action) action = '';
     if (!frm.getAttribute("onsubmit") && (action.indexOf('javascript:')!=0)){
       frm.onsubmit = doLockAll;
     }
*/
   }
 }
}

function doLockAll() {
  var i;
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("rel") != "external"){
     anchor.onclick = function(){return false;};
   }
 }
 var forms = document.getElementsByTagName("form");
 for (i=0; i<forms.length; i++) {
   var frm = forms[i];
   if (frm.getAttribute("rel") != "external"){
     frm.onsubmit = function(){return false;};
   }
 }
 setTimeout('doUnLockAll()',10000)
}

/**
 * Message displayed on timeout
 */
function logoutMessage(element, text)
{
  var s=s_gi(s_account);
  s.linkTrackVars = 'prop18';
  s.prop18 = 'popup';
  s.tl(element, 'o', 'Timeout Popup');
  confirmOption(element, '', text, '300', 'OK', '');
}

function doUnLockAll() {
  var i;
  var evt;
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   evt = '' + anchor.getAttribute("onclick");
   //alert(evt.indexOf('return false'));
   if ((anchor.getAttribute("rel") != "external") && (evt.indexOf('return false') != -1)){
     anchor.onclick = '';
   }
 }

 var forms = document.getElementsByTagName("form");
 for (i=0; i<forms.length; i++) {
   var frm = forms[i];
   evt = '' + frm.getAttribute("onsubmit");
   //alert(evt.indexOf('return false'));
   if ((frm.getAttribute("rel") != "external")  && (evt.indexOf('return false') != -1)){
     frm.onsubmit = '';
   }
 }

}

function posLeft() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset:document.documentElement && document.documentElement.scrollLeft? document.documentElement.scrollLeft:document.body.scrollLeft? document.body.scrollLeft:0;}
function posTop() {return typeof window.pageYOffset != 'undefined' ? window.pageYOffset:document.documentElement && document.documentElement.scrollTop? document.documentElement.scrollTop: document.body.scrollTop?document.body.scrollTop:0;}
function pageWidth() {return window.innerWidth != null? window.innerWidth: document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth:document.body != null? document.body.clientWidth:null;}
//function pageHeight() {return window.innerHeight != null? window.innerHeight: document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight:document.body != null? document.body.clientHeight:null;}

var dialogBox = null;
var visibleBoxWidth = 300;

function ha() {
	window.location.reload();
  //alert(document.getElementById('sss'));
  formElementsVisibility('visible');
  //Bad Patch for Flexicieling Only. No other option :(
  if(document.getElementById('HiddenTextBox') != null && document.getElementById('msisdn1_new') != null && document.getElementById('msisdn1_new').value != 'other')
  document.getElementById('HiddenTextBox').style.visibility = 'hidden'
  document.body.removeChild(dialogBox);
}

/**
  * Returns parent form of given element
  *
  * @param Node element
  * @return Node
  */
function getParentForm(element) {
  var node = element;
  while (element && element.tagName != 'FORM')
    element = element.parentNode;
  return element;
}

function getElementByName(name) {
  var parent = arguments.length > 1 ? arguments[1] : document.documentElement;
  var retVal, i;
  if (parent.nodeName.toUpperCase() == name.toUpperCase())
    return parent;
  if (parent.hasChildNodes()) {
    for (i = 0; i < parent.childNodes.length; i++) {
      retVal = getElementByName(name, parent.childNodes.item(i));
      if (retVal = getElementByName(name, parent.childNodes.item(i))) {
        return retVal;
      }
    }
  }
  return false;
}

/**
  * Function for enhanced confirm dialogs
  *
  * @param Node element Element from which it is called
  * @param string title Title of Dialog
  * @param string text Dialog text
  * @param string button1Text Text for the first button
  * @param string button1Link Link for the first button; It supports the following
  *   special values:
  *     ''         (no link, only remove the dialog)
  *     'link'     use attribute href
  *     'submit'   submits form in which element is found
  * The target link
  */
function confirmOption(element, title, text, width) {
  var h = getElementByName('body').offsetHeight + 200;

  formElementsVisibility('hidden');
  dialogBox=document.createElement("div");
  var inactArea=document.createElement("div");
  inactArea.style.position='absolute';
  inactArea.style.top=0;
  inactArea.style.left=0;
  inactArea.style.width=(pageWidth()-16)+'px';
  inactArea.style.height=h+'px';
  inactArea.style.background='#bbb';
  inactArea.style.filter='alpha(opacity=50)'; // IE
  inactArea.style.opacity='0.50'; // FF

  var actArea=document.createElement("div");
  actArea.style.position='absolute';
  actArea.style.top=(posTop()+310)+'px';            // top offset always fixed
  actArea.style.left=(posLeft()+((pageWidth()-visibleBoxWidth)/2)-((width - 300)/2))+'px';
  actArea.style.width= width + 'px';
  actArea.style.background='white';
  actArea.style.border='1px solid black';
  var paddingLeft = 120 - ((arguments.length - 5)/2 * 30);
  var html = '<div class="act-area">' +
    '<h3>' + title + '</h3><a href="javascript: ha()" alt="zavřít okno" title="zavřít okno"></a>' +
    '<div class="cleaner"></div>' +
    '</div><span class="act-area"></span><span class="act-area">'
      + text + '</span><div class="button-area" style="padding-left: ' + paddingLeft + 'px">';
  var action = '';
  for (i = 4; i < arguments.length; i += 2) {
    if (arguments[i+1]) {
      if (arguments[i+1] == 'link')
        action = "window.location = '" + element.getAttribute('href') + "'";
      else if (arguments[i+1] == 'submit') {
        currentForm = getParentForm(element);
        action = 'currentForm.submit()';
      }
      else
        action = "window.location = '" + arguments[i+1] + "'";
      html +=
        '<a class="textBtnRed" onclick="ha(); ' + action + '"><span>'
        + arguments[i] + '</span></a>';
    }
    else
      html += '<a class="textBtnRed" onclick="ha()"><span>' +
        arguments[i] + '</span></a>';
  }
  html += '<br class="clear"/></div>';
  actArea.innerHTML += html;
  dialogBox.appendChild(inactArea);
  dialogBox.appendChild(actArea);
  document.body.appendChild(dialogBox);

  return false;
  //return (confirm(text)) ? true : false;
}

/**
  * Changes visibility of form input elements
  *
  * @param string visibility 'visible' | 'hidden'
  */
function formElementsVisibility(visibility) {
  if (!document.getElementsByTagName) return;
  var elements = document.getElementsByTagName('input');
  for (var i = 0; i < elements.length; i++)
    elements[i].style.visibility = visibility;
}

function unhideElements(elements) {
  for (var i = 0; i < elements.length; i++)
    elements[i].style.visibility = 'visible';
}

function checkLogin(element){
  var msisdn = document.forms[1].msisdn.value;
  var passwd = document.forms[1].passwd.value.length;
  var ccCheckRegExp = /^\d{9}$/;
  if ( passwd<4 || ! ccCheckRegExp.test(msisdn) ) {
    alert(wrongFormatErr);
    return false;
  } else {
    var s=s_gi(s_account);
    s.linkTrackVars = 'events,prop19';
    s.linkTrackEvents = 'event11';
    s.events = 'event11';
    s.prop19 = window.location;
    s.tl(element, 'o', 'Login');
    return doLockAll();
  }
}

function check2in1passwd(passwd, msg){
    if(isNaN(passwd.value) || passwd.value.length!=5 || passwd.value.charAt(0)=='0'){
        alert(msg);
        passwd.focus();
        return false;
    }
    return true;
}

function checksimnumber(item, msg){
    if(isNaN(item.value) || item.value.length!=13){
        alert(msg);
        item.focus();
        return false;
    }
    return true;
}

function resContent(){
    var a;
    var b;
    var c;
    var max;
    if(!document.getElementById) return;
    a = (document.getElementById('moreinfo')!=null) ? document.getElementById('moreinfo').offsetHeight : 0;
    b = (document.getElementById('subnav')!=null) ? document.getElementById('subnav').offsetHeight : 0;
    max = (a>b) ? a : (b-20);
    c = document.getElementById('content');
    if (c) {
      if (max > c.offsetHeight) {
        c.style.height = '' + max + 'px';   // height of banner from CSS styles
      }
    }
    c = document.getElementById('content_homepage');
    if (c) {
      if (max > c.offsetHeight) {
        max = (a>b) ? a : (b-100);
        c.style.height = '' + max + 'px';   // height of banner from CSS styles
      }
    }
}

function showDebug(){
  zi = document.getElementById("dbg");
  zi.style.display = (zi.style.display=='block' || zi.style.display=='') ? 'none': 'block';
}

function confirmQ1Offer(m) {
  var agree = confirm(m);
  if (agree)
    return true;
  else
    return false;
}

function vpncheck(obj) {
  var i;
  var cnt = 0;

  for (i = 1; document.getElementById('vpn' + i); i++) {
    if (document.getElementById('vpn' + i).checked) cnt++;
  }
  if (cnt > 4) {
    alert(vpnErrorTxt);
    obj.checked = false;
  }
}

function evalPwd(pwd) {
  var regex = /^[0]{4,6}$|^[1]{4,6}$|^[2]{4,6}$|^[3]{4,6}$|^[4]{4,6}$|^[5]{4,6}$|^[6]{4,6}$|^[7]{4,6}$|^[8]{4,6}$|^[9]{4,6}$|^1234$|^12345$|^123456$/;
  if(pwd.length > 3) {
    var weak = document.getElementById('iWeak');
    var strong = document.getElementById('iStrong');
    if(regex.test(pwd)) {
      weak.style.backgroundColor = '#ff0033';
      weak.style.fontWeight = 'bold';
      weak.style.color = '#fff';
      strong.style.backgroundColor = '#f1f1f1';
      strong.style.fontWeight = 'normal';
      strong.style.color = '#adadad';
    } else {
      weak.style.backgroundColor = '#339900';
      weak.style.fontWeight = 'normal';
      weak.style.color = '#339900';
      strong.style.backgroundColor = '#339900';
      strong.style.fontWeight = 'bold';
      strong.style.color = '#fff';
    }
  }
}

function gspCountCheck(obj, max) {
  var i, cnt = 0;
  for (i = 1; document.getElementById('idx' + i); i++) {
    if (document.getElementById('idx' + i).checked) cnt++;
  }
  if (cnt > max) {
    alert(gspCountCheckErrorTxt);
    obj.checked = false;
  }
}

/**
 * Shows the warning message in control panel
 *
 * @param Element element the <select> element
 * @param string value1 Select value for which the message shall be shown
 * @param string message1 Message corresponding to the value
 * @param string value2 ...
 */
function cpOnChangeMessage(element) {
  var i, j, warning;
  for (i = 1; i < arguments.length; i++)
    if (arguments[i] == element.value) {
      if (warning = document.getElementById('cp-warning')) {
        nodes = warning.childNodes;
        for (j = 0; nodes.length; j++)
          warning.removeChild(nodes.item(j));
        warning.appendChild(document.createTextNode(arguments[i+1]));
        warning.className = 'warning visible';
      }
      return;
    }
  cpHideMessage();
}

/**
 * Hides warning message shown above the control panel
 */
function cpHideMessage() {
  var warning;
  if (warning = document.getElementById('cp-warning'))
    warning.className = 'warning invisible';
}

/**
 * Returns HTTP object to be used with AJAX
 */
function get_request_object()
{
  var http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
      http_request.overrideMimeType('text/xml');
    }
  } else if (window.ActiveXObject) { // IE
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
         http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }
  return http_request;
}

/**
 * Displays gadget of given type (using AJAX)
 *
 * @param string type Type of gadget
 * @param string URL parameters to be passed to the gadget
 * @param string element_id Id of the element to which output should be written
 */
function load_gadget(type, url_parameters, element_id)
{
  var http_request;
  if (http_request = get_request_object()) {
    http_request.onreadystatechange = function() {
      if (http_request.readyState == 4) {
        document.getElementById(element_id).innerHTML =
          http_request.responseText.replace(/.*<gadget>(.*)<\/gadget>/, "$1");
      }
    }
    http_request.open('GET', 'gadget.php?type=' + type + url_parameters, true);
    http_request.send(null);
  }
}

/**
 * Displays cep of given type (using AJAX)
 *
 * @param string channel_id CEP channel id
 * @param string url_parameters URL parameters to be passed to the CEP
 * @param string element_id Id of the element to which output should be written
 */
function load_cep(channel_id, url_parameters, element_id)
{
  var http_request;
  if (http_request = get_request_object()) {
    http_request.onreadystatechange = function() {
      if (http_request.readyState == 4) {
        document.getElementById(element_id).innerHTML =
          http_request.responseText.replace(/.*<cep>(.*)<\/cep>/, "$1");
      }
    }
    http_request.open('GET', 'cep_gadget.php?channel_id=' + channel_id + url_parameters, true);
    http_request.send(null);
  }
}

/**
 * Displays survey (using AJAX)
 *
 * @param string url_parameters URL parameters to be passed to the survey
 * @param string element_id Id of the element to which output should be written
 */
function load_survey(url_parameters, element_id)
{
  var http_request;
  if (http_request = get_request_object()) {
    http_request.onreadystatechange = function() {
      if (http_request.readyState == 4) {
        document.getElementById(element_id).innerHTML =
          http_request.responseText.replace(/.*<survey>(.*)<\/survey>/, "$1");
      }
    }
    http_request.open('GET', 'survey.php?' + url_parameters, true);
    http_request.send(null);
  }
}

function recommend_submit(no_category, no_email, no_message, no_inputs)
{
  var error = false;
  var message = document.getElementById('message').value.replace(/\s+$/, '');
  var mail = document.getElementById('mail').value.replace(/\s+$/, '');
  var list = document.getElementById('area');
  var selectedIndex = list.selectedIndex;
  var listVal = list.options[selectedIndex].text.replace(/\s+$/, '');

  if (listVal == '')
      error = no_category;
  else if (mail == '' && message == '')
    error = no_inputs;
  else if (mail == '')
    error = no_email;
  else if (message == '')
    error = no_message;
  if (error != '')
    confirmOption(document, '', error, '300', 'OK', '');
  else
    document.getElementById('recommend_form').submit();
}

/**
 * Appends tag to given node
 *
 * @param DOMNode parent Parent node
 * @param String nodeName Name of the new node
 * @param String text Text content of the tag
 * @param Array attributes [OPTIONAL]
 */
function addTag(parent, nodeName)
{
  var i, child;
  child = document.createElement(nodeName);
  if (arguments.length >= 3)
    child.appendChild(document.createTextNode(arguments[2]));
  if (arguments.length == 4)
    setAttributes(child, arguments[3]);
  parent.appendChild(child);
  return child;
}

/**
 * Appends tag after given element
 */
function addTagAfter(preceedingTag, nodeName)
{
  var i, child;
  child = document.createElement(nodeName);
  if (arguments.length >= 3)
    child.appendChild(document.createTextNode(arguments[2]));
  if (arguments.length == 4)
    setAttributes(child, arguments[3]);
  if (preceedingTag.nextSibling)
    preceedingTag.parentNode.insertBefore(child, preceedingTag.nextSibling);
  else
    preceedingTag.parentNode.appendChild(child);
  return child;
}

/**
 * Sets attributes of given node
 *
 * @param DOMNode tag
 * @param array attributes [name, value, ...]
 */
function setAttributes(tag, attributes)
{
  var i;
  for (i = 0; i < attributes.length; i += 2) {
    if (attributes[i] == 'class')
      tag.className = attributes[i+1];
    else {
      if (attributes[i] == 'colspan')
        tag.colSpan = attributes[i+1];
      tag.setAttribute(attributes[i], attributes[i+1]);
    }
  }
}

/**
 * Adds hidden input field has_js to form or extends the <a> href attribute
 *
 * @param string id Id of form or the <a> tag
 */
function saveJsStatus(id)
{
  var el = document.getElementById(id);
  var input = document.createElement('input');
  if (el.tagName == 'A') {
    var href = el.getAttribute('href');
    var sep = href.indexOf('?') == -1 ? '?' : '&';
    el.setAttribute('href', href + sep + 'has_js=yes');
  }
  else {
    input.setAttribute('type', 'hidden');
    input.setAttribute('name', 'has_js');
    input.setAttribute('value', 'yes');
    el.appendChild(input);
  }
}

function prelimTasksFan(checkbox,textbox,div,text){

    if(checkbox.checked == false)
      checkbox.checked = true;
    div.innerHTML  = text;
    return true;
}

function checkedFan(checkbox,textbox,div,text,text1) {

    if(checkbox.checked == false)
      div.innerHTML  = text1;
    else
      div.innerHTML  = text;
    return true;
}

function checkMsisdn(msisdn,msisdnSelf){

    msisdnVal = msisdn.value;
    err = 0;
    if(msisdnVal == '') return 8914;
    if(msisdnVal.length < 9) return 8911;

    var regExp = /^[A-Za-z]$/;
    for(var i = 0; i < msisdnVal.length; i++){
      if (msisdnVal.charAt(i).match(regExp)){
         return 8912;
         break;
      }
    }

    if('420'.msisdnVal == msisdnSelf) return 8913;

    if(msisdnVal.substring(0,1)  != '2' && msisdnVal.substring(0,2) != '60'  && msisdnVal.substring(0,1) != '7' && msisdnVal.substring(0,2) != '31' && msisdnVal.substring(0,2) != '32' && msisdnVal.substring(0,2) != '38' && msisdnVal.substring(0,2) != '39' && msisdnVal.substring(0,2) != '37' && msisdnVal.substring(0,2) != '35' && msisdnVal.substring(0,2) != '41' && msisdnVal.substring(0,2) != '47' && msisdnVal.substring(0,2) != '48' && msisdnVal.substring(0,2) != '49' && msisdnVal.substring(0,2) != '46' && msisdnVal.substring(0,2) != '56' && msisdnVal.substring(0,2) != '51' && msisdnVal.substring(0,2) != '53' && msisdnVal.substring(0,2) != '54' && msisdnVal.substring(0,2) != '57' && msisdnVal.substring(0,2) != '58' && msisdnVal.substring(0,2) != '55' && msisdnVal.substring(0,2) != '59'){

          //return 8841;
          return 8956;
    }

    return err;

}
function disableEnterKey(e)
{
     var key;

     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox

     return (key != 13);
}

function submit_login_form()
 {
   document.getElementById('account').action='%WSC%login.php';
   document.getElementById('account').submit();
 }

