/*
    // dimaninc general js functions

    // 2006/03/28
        * getHTTPRequestObject() added
        * diXMLRequest.get() and .post() added

    // 2006/02/28
        * standard escape() rewritten

    // 2006/02/20
        * is_ie added

    // 2006/02/11
        * getLeft(), getTop() added
        * _px() improved

    // 2006/02/08
        * addEvent() added
        * _px() added

    // 2006/02/06
        * the first version of this shit
*/

var is_ie = (document.all) ? true : false;

var agt = navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);
var is_gecko = (agt.indexOf('gecko') != -1);
var is_ie4up = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1) && (is_major >= 4));
var is_opera = (agt.indexOf("opera") != -1);

function isEmpty(str)
{
  if (str == null || str == "" || isNaN(str))
    return true;
  else
    return false;
}

function _ge(eid)
{
  return document.getElementById(eid);
}

function addEvent(elem, evname, func)
{
  if (elem.attachEvent)
  {
    //elem.attachEvent("on" + evname, func);
    //alert("elem.on"+evname+"=func;");
    eval("elem.on"+evname+"=func;");
  }
  else
    elem.addEventListener(evname, func, false); //true
}

function _add_event(elem, evname, func)
{
  if (elem.attachEvent)
  {
    //elem.attachEvent("on" + evname, func);
    //alert("elem.on"+evname+"=func;");
    eval("elem.on"+evname+"=func;");
  }
  else
    elem.addEventListener(evname, func, false); //true
}

function delEvent(elem, evname, func)
{
  if (elem.attachEvent)
  {
    eval("elem.on"+evname+"=null;");
  }
  else
    elem.removeEventListener(evname, func, false); //true
}

function _px(px)
{
  var x = parseInt(px, 10);

  if (isNaN(x)) x = 0;

  return x;
}

function getLeft(o)
{
  var x = o.offsetLeft;
  while (o = o.offsetParent) x += o.offsetLeft;
  return x;
}

function getTop(o)
{
  var y = o.offsetTop;
  while (o = o.offsetParent) y += o.offsetTop;
  return y;
}

function _get_left(o)
{
  var x = o.offsetLeft;
  while (o = o.offsetParent) x += o.offsetLeft;
  return x;
}

function _get_top(o)
{
  var y = o.offsetTop;
  while (o = o.offsetParent) y += o.offsetTop;
  return y;
}

/*
function getTop(o) {
   var y = o.offsetTop;
   while (o.offsetParent)
    {
      y += o.offsetTop;
      o = o.offsetParent;
    }
   return y
}
*/

function get_screen_dimensions(what)
{
  var viewportwidth;
  var viewportheight;

  if (typeof window.innerWidth != 'undefined')
  {
    viewportwidth = window.innerWidth;
    viewportheight = window.innerHeight;
  }
  else if (typeof document.documentElement != 'undefined'
           && typeof document.documentElement.clientWidth !=
           'undefined' && document.documentElement.clientWidth != 0)
  {
    viewportwidth = document.documentElement.clientWidth;
    viewportheight = document.documentElement.clientHeight;
  }
  else
  {
    viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
    viewportheight = document.getElementsByTagName('body')[0].clientHeight;
  }

  switch (what)
  {
    case 'x':
    case 'w':
      return viewportwidth;

    case 'y':
    case 'h':
      return viewportheight;

    default:
      return [viewportwidth,viewportheight];
  }
}

// escape function
var escape_trans = [];
for (var i = 0x410; i <= 0x44F; i++) escape_trans[i] = i - 0x350; // À-ßà-ÿ
escape_trans[0x401] = 0xA8;    // ¨
escape_trans[0x451] = 0xB8;    // ¸

var escapeOrig = window.escape;

window.escape = function(str)
{
  var ret = [];
  var str1 = str.toString();

  for (var i = 0; i < str1.length; i++)
  {
    var n = str1.charCodeAt(i);
    if (typeof escape_trans[n] != 'undefined') n = escape_trans[n];
    if (n <= 0xFF) ret.push(n);
  }
  return escapeOrig(String.fromCharCode.apply(null, ret));
}

function getHTTPRequestObject()
{
  var xmlHttpRequest = false;

  if (typeof ActiveXObject != 'undefined')
  {
    try {
      xmlHttpRequest = new ActiveXObject('Microsoft.XMLHTTP');
    } catch(e) {}

    if (!xmlHttpRequest) try {
      xmlHttpRequest = new ActiveXObject('Msxml2.XMLHTTP');
    } catch(e) {}
  }
  else if (typeof XMLHttpRequest != 'undefined')
  {
    xmlHttpRequest = new XMLHttpRequest();
  } else
  {
    xmlHttpRequest = false;
  }

  return xmlHttpRequest;
}

var diXMLRequest =
{
  get : function (url, callback)
  {
    var _getter = getHTTPRequestObject();
    _getter.open("GET", url, true);

    _getter.onreadystatechange = function() {
      if (_getter.readyState == 4)
      {
        callback(_getter.responseXML);
      }
    }

    _getter.send(null)
  },

  post : function (url, form, callback)
  {
    var _poster = getHTTPRequestObject();

    _poster.open("POST", url, true);
    _poster.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    _poster.setRequestHeader('Connection', 'close');
    _poster.send(form);

    _poster.onreadystatechange = function() {
      if (_poster.readyState == 4)
      {
        callback(_poster.responseXML);
      }
    };

    //if (!is_ie) _poster.send(null);
  }
}

function MM_preloadImages() {
 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
   var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
   if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}}

var __correct_latin_symbols_regexp = new RegExp("^[a-z0-9-_.]+$", "i");
var __correct_digits_regexp = new RegExp("^[0-9.,]+$", "i");
var __correct_email_regexp = new RegExp('^[0-9a-z]([-_.]*[0-9a-z])*@[0-9a-z]([-._]*[0-9a-z])*[.]{1}[a-z]{2,4}$', 'i');

function check_correct_latin_symbols(s)
{
  return __correct_latin_symbols_regexp.test(s);
}

function check_correct_digits(s)
{
  return __correct_digits_regexp.test(s);
}

function check_correct_email(s)
{
  return __correct_email_regexp.test(s);
}

function mysprintf(num, afterdot)
{
  var d = Math.pow(10, afterdot);
  num = Math.round(num * d) / d;

  var a = num.toString().split('.');
  if (!a[1]) a[1] = '';

  while (a[1].length < afterdot) a[1] += '0';

  return a[0]+'.'+a[1];
}

function str_cut_end(s, max_len)
{
  var trailer = arguments[2] || '...';

  if (s.length > max_len)
    s = s.substr(0, max_len - trailer.length)+trailer;

  return s;
}

function in_array(search_term, ar)
{
  var i = ar.length;

  if (i > 0)
  {
     do
     {
       if (ar[i] == search_term)
       {
         return true;
       }
     } while (i--);
  }

  return false;
}

function mysprintf(num, afterdot)
{
  var d = Math.pow(10, afterdot);
  num = Math.round(num * d) / d;

  var a = num.toString().split('.');
  if (!a[1]) a[1] = '';

  while (a[1].length < afterdot) a[1] += '0';

  return a[0]+'.'+a[1];
}


function getQueryVariable(variable)
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");

    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return null;
}

function array_unique(ar)
{
  var key = '', tmp_ar = {}, val = '';

  var __array_search = function(needle, haystack)
  {
    var fkey = '';

    for (fkey in haystack)
    {
      if (haystack.hasOwnProperty(fkey))
      {
        if ((haystack[fkey] + '') === (needle + ''))
        {
          return fkey;
        }
      }
    }

    return false;
  };

  for (key in ar)
  {
    if (ar.hasOwnProperty(key))
    {
      val = ar[key];
      if (false === __array_search(val, tmp_ar))
      {
        tmp_ar[key] = val;
      }
    }
  }

  return tmp_ar;
}

function lead0(x)
{
  x += '';

  return x.length == 1 ? '0'+x : x;
}

function get_xml_text(e)
{
  var xxx = e.firstChild;

  if (typeof xxx == 'undefined' || !xxx)
    return false;

  if (typeof xxx.nodeValue != 'undefined' && xxx.nodeValue)
  {
    return xxx.nodeValue;
  }
  else if (typeof xxx.textContent != 'undefined' && xxx.textContent)
  {
    return xxx.textContent;
  }

  return '';
}

function di_xml2array(r)
{
  var e = r.firstChild;
  var ar = [];

  do
  {
    ar[e.nodeName] = get_xml_text(e);
  }
  while (e = e.nextSibling);

  return ar;
}

function array_splice (arr, offst, lgth, replacement)
{
    // Removes the elements designated by offset and length and replace them with supplied array
    //
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/array_splice
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Theriault
    // %        note 1: Order does get shifted in associative array input with numeric indices,
    // %        note 1: since PHP behavior doesn't preserve keys, but I understand order is
    // %        note 1: not reliable anyways
    // %        note 2: Note also that IE retains information about property position even
    // %        note 2: after being supposedly deleted, so use of this function may produce
    // %        note 2: unexpected results in IE if you later attempt to add back properties
    // %        note 2: with the same keys that had been deleted
    // -    depends on: is_int
    // *     example 1: input = {4: "red", 'abc': "green", 2: "blue", 'dud': "yellow"};
    // *     example 1: array_splice(input, 2);
    // *     returns 1: {0: "blue", 'dud': "yellow"}
    // *     results 1: input == {'abc':"green", 0:"red"}
    // *     example 2: input = ["red", "green", "blue", "yellow"];
    // *     example 2: array_splice(input, 3, 0, "purple");
    // *     returns 2: []
    // *     results 2: input == ["red", "green", "blue", "purple", "yellow"]
    // *     example 3: input = ["red", "green", "blue", "yellow"]
    // *     example 3: array_splice(input, -1, 1, ["black", "maroon"]);
    // *     returns 3: ["yellow"]
    // *     results 3: input == ["red", "green", "blue", "black", "maroon"]

    var _checkToUpIndices = function (arr, ct, key) {
        // Deal with situation, e.g., if encounter index 4 and try to set it to 0, but 0 exists later in loop (need to
        // increment all subsequent (skipping current key, since we need its value below) until find unused)
        if (arr[ct] !== undefined) {
            var tmp = ct;
            ct += 1;
            if (ct === key) {
                ct += 1;
            }
            ct = _checkToUpIndices(arr, ct, key);
            arr[ct] = arr[tmp];
            delete arr[tmp];
        }
        return ct;
    };

    if (replacement && typeof replacement !== 'object') {
        replacement = [replacement];
    }
    if (lgth === undefined) {
        lgth = offst >= 0 ? arr.length - offst : -offst;
    } else if (lgth < 0) {
        lgth = (offst >= 0 ? arr.length - offst : -offst)  + lgth;
    }

    if (!(arr instanceof Array)) {
        /*if (arr.length !== undefined) { // Deal with array-like objects as input
        delete arr.length;
        }*/
        var lgt = 0, ct = -1, rmvd = [], rmvdObj = {}, repl_ct=-1, int_ct=-1;
        var returnArr = true, rmvd_ct = 0, rmvd_lgth = 0, key = '';
        // rmvdObj.length = 0;
        for (key in arr) { // Can do arr.__count__ in some browsers
            lgt += 1;
        }
        offst = (offst >= 0) ? offst : lgt + offst;
        for (key in arr) {
            ct += 1;
            if (ct < offst) {
                if (this.is_int(key)) {
                    int_ct += 1;
                    if (parseInt(key, 10) === int_ct) { // Key is already numbered ok, so don't need to change key for value
                        continue;
                    }
                    _checkToUpIndices(arr, int_ct, key); // Deal with situation, e.g.,
                    // if encounter index 4 and try to set it to 0, but 0 exists later in loop
                    arr[int_ct] = arr[key];
                    delete arr[key];
                }
                continue;
            }
            if (returnArr && this.is_int(key)) {
                rmvd.push(arr[key]);
                rmvdObj[rmvd_ct++] = arr[key]; // PHP starts over here too
            } else {
                rmvdObj[key] = arr[key];
                returnArr    = false;
            }
            rmvd_lgth += 1;
            // rmvdObj.length += 1;

            if (replacement && replacement[++repl_ct]) {
                arr[key] = replacement[repl_ct];
            } else {
                delete arr[key];
            }
        }
        // arr.length = lgt - rmvd_lgth + (replacement ? replacement.length : 0); // Make (back) into an array-like object
        return returnArr ? rmvd : rmvdObj;
    }

    if (replacement) {
        replacement.unshift(offst, lgth);
        return Array.prototype.splice.apply(arr, replacement);
    }
    return arr.splice(offst, lgth);
}

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}


function toggle_hotel_rooms(hotel_id)
{
  var e = _ge('hotel_rooms_'+hotel_id);
  var a = _ge('hotel_a_'+hotel_id);

  if (e && a)
  {
    var txt = e.style.display != 'block' ? 'Hide rooms' : 'Show rooms';

    if (typeof a.value != 'undefined')
      a.value = txt;
    else if (typeof a.innerHTML != 'undefined')
      a.innerHTML = txt;

    e.style.display = e.style.display != 'block' ? 'block' : 'none';
  }
}

function make_order(hotel_id)
{
  var total_beds = 0;
  var party_size = getQueryVariable('party_size');
  party_size = party_size ? parseInt(party_size) : 0;
  if (!party_size) return;
  var duration = getQueryVariable('duration');
  duration = duration ? parseInt(duration) : 0;
  if (!duration) return;
  var flexibility = getQueryVariable('flexibility');
  flexibility *= 1;

  if (!d1_ar[hotel_id]) return;

  var cost = 0;
  var q = 'target_id=';

  if (rooms_ar[hotel_id])
  { //rooms
    for (var i in rooms_ar[hotel_id])
    {
      var _id = rooms_ar[hotel_id][i].id;
      var _beds = rooms_ar[hotel_id][i].beds;
      var _price = rooms_ar[hotel_id][i].price;
      var _e = _ge('room_cb_'+_id);

      if (_e && _e.checked)
      {
        cost += _price;
        total_beds += _beds;

        q += _id+',';
      }
    }

    if (total_beds < party_size)
    {
      alert('You have chosen rooms with '+total_beds+' beds summary, but your party size is '+party_size+'!');
      return;
    }

    var book_type = 'room';
  }
  else
  { //whole hotel
    q += hotel_id;

    var book_type = 'hotel';
  }

  if (q.substr(q.length - 1, 1) == ',') q = q.substr(0, q.length - 1);

//  q += '&d1='+d1_ar[hotel_id]+'&duration='+duration+'&flexibility='+flexibility;
	q += '&d1='+d1_ar[hotel_id]+'&duration='+duration+'&flexibility='+flexibility+'&party_size='+party_size;

  //window.location.href = ''+book_path+'/?type='+book_type+'&'+q;
  window.location.href = ''+book_path+'/?type='+book_type+'&'+q;
}

function isleapyear(year)
{
  return year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ? true : false;
}

function get_wd(date_obj)
{
  var x = date_obj.getDay();
  if (x == 0) x = 7;

  return x;
}

function get_yday(date_obj)
{
  return date_obj && typeof date_obj == 'object' ? Math.floor((date_obj - (new Date(date_obj.getFullYear(), 0, 1))) / 86400000) : 0;
}

function get_big_yday(y, yday)
{
  if (typeof yday == 'undefined')
  {
    if (!y || typeof y != 'object')
      return 0;

    var yday = get_yday(y);
    y = y.getFullYear();
  }

  yday += '';

  while (yday.length < 3)
    yday = '0'+yday;

  return (y+''+yday)*1;
}

function get_time(date_obj)
{
  return date_obj && typeof date_obj == 'object' ? Math.round(date_obj.getTime() / 1000) : 0;
}

