var Global_DownloadLock = false;

function download(galleryId, res, gpath) {
  preDownload();
  //Global_DownloadLock = true;
  var frm = document.getElementById("downloadIframe");
    if (frm) {
      frm.parentNode.removeChild(frm);
    }
  frm = document.createElement("IFRAME");
  document.body.appendChild(frm);
  frm.id = "downloadIframe";
  frm.style.visibility = "hidden";
  frm.style.width = "1px";
  frm.style.height = "1px";
  //alert("/download.php?g="+galleryId+"&r="+res+"$gpath="+gpath);
  frm.src = "/download.php?g="+galleryId+"&r="+res+"&gpath="+gpath;
  
}

function preDownload() {
    if (Global_DownloadLock) {
      return;
    }
  var d = document.getElementById("downloadDiv");
  d.style.display = d.style.display == "none" ? "" : "none";
    if (d.style.display == "none") {
      return;
    }
  var r = getAbsolutePos(document.getElementById("dd_mark"));
  d.style.left = r.x+"px";
  d.style.top = (r.y+30)+"px";
}

function getAbsolutePos(obj) {
  var SL = 0, ST = 0;
  var is_div = /^div$/i.test(obj.tagName);
  if (is_div && obj.scrollLeft)
    SL = obj.scrollLeft;
  if (is_div && obj.scrollTop)
    ST = obj.scrollTop;
  var r = { x: obj.offsetLeft - SL, y: obj.offsetTop - ST };
    if (obj.offsetParent) {
      var tmp = this.getAbsolutePos(obj.offsetParent);
      r.x += tmp.x;
      r.y += tmp.y;
    }
  return r;
}

var Global_scrollDir = 0;
var Global_timer = 0;

function scrollDiv() {
  var d = document.getElementById("videoDiv");
  d.scrollLeft += Global_scrollDir;
  window.setTimeout(scrollDiv, 20);
}

function startScrollDiv(offset) {
  Global_scrollDir = offset;
  Global_timer = window.setTimeout(scrollDiv, 20);
}

function stopScrollDiv() {
  window.clearTimeout(Global_timer);
  Global_scrollDir = 0;
  Global_timer = 0;
}

function switchNewsText(id) {
  var sp1 = document.getElementById("preview_"+id);
  var sp2 = document.getElementById("fulltext_"+id);
  sp1.style.display = sp1.style.display == "none" ? "" : "none";
  sp2.style.display = sp2.style.display == "none" ? "" : "none";
}

function addTofavorite(id) {
  var responce = sendRequest("addtofavorite.php?id="+id);
  alert(responce);
}

function removeFromFavorite(id) {
  var responce = sendRequest("removefromfavorite.php?id="+id);
  alert(responce);
}

function sendRequest (page, requestBody, handler) {
  var request = new aXmlHttpRequest(page, "post");
  var data = "";
  request.body = requestBody;
    try {
      HTTP_CLIENT = new aXmlHttpClient();
      HTTP_CLIENT.init();
        if (handler) {
          HTTP_CLIENT.callAsync (request, handler);
        }
        else {
          data = HTTP_CLIENT.call (request);
        }
    }
    catch (e) {
      debug(e+"\n"+page+"\n"+requestBody);
    }
  return data;
}

var GlobalSlideShow = false;
var GlobalSlideShowResolution = 800;
var GlobalSlideShowTimerId = -1;
var GlobalSlideShowTimeOut = 20*1000;
var GlobalSlideShowImageIdx = -1;
var GlovalSlideShowImages = new Array();

//function

function startShow(imageIdx, timeout) {
  var links = document.getElementsByTagName("A");
    for (var i = 0; i < links.length; i++) {
      if (links[i].rel == "lightbox[girls_"+GlobalSlideShowResolution+"]") {
        GlovalSlideShowImages[GlovalSlideShowImages.length] = links[i];
      }
    }
  GlobalSlideShow = true;
  GlobalSlideShowImageIdx = imageIdx ? imageIdx : 0;
  document.getElementById("slide0").style.backgroundImage = "url(images/slide_0.gif)";
  document.getElementById("slide1").style.backgroundImage = "url(images/slide_1_.gif)";
  document.getElementById("slide2").style.backgroundImage = "url(images/slide_2.gif)";
  document.getElementById("slide3").style.backgroundImage = "url(images/slide_3.gif)";
  GlobalSlideShowTimeOut = 20*1000;
  //changeTimeout(timeout ? timeout : 20);

		//alert(GlovalSlideShowImages[GlobalSlideShowImageIdx]);
      myLightbox.start(GlovalSlideShowImages[GlobalSlideShowImageIdx]);

  GlobalSlideShowTimerId = window.setInterval(continueShow, GlobalSlideShowTimeOut);
}

function continueShow () {
  GlobalSlideShowImageIdx++;//alert(GlobalSlideShowImageIdx+"|"+GlovalSlideShowImages.length);
    if (GlobalSlideShowImageIdx >= GlovalSlideShowImages.length) {
      stopShow();
      return;
    }
  myLightbox.changeImage(GlobalSlideShowImageIdx);
  //window.setTimeout(continueShow, GlobalSlideShowTimeOut);
}

function stopShow () {
  document.getElementById("slide0").style.backgroundImage = "url(images/slide_0_.gif)";
  document.getElementById("slide1").style.backgroundImage = "url(images/slide_1.gif)";
  document.getElementById("slide2").style.backgroundImage = "url(images/slide_2.gif)";
  document.getElementById("slide3").style.backgroundImage = "url(images/slide_3.gif)";
  myLightbox.updateNav();
  GlobalSlideShow = false;
  GlovalSlideShowImages = new Array();
  GlobalSlideShowTimeOut = 20*1000;
  window.clearInterval(GlobalSlideShowTimerId);
  GlobalSlideShowTimerId = -1;
  GlobalSlideShowImageIdx = -1;
}

function changeTimeout (time) {
  GlobalSlideShowTimeOut = time*1000;
  document.getElementById("slide0").style.backgroundImage = "url(images/slide_0.gif)";
  document.getElementById("slide1").style.backgroundImage = "url(images/slide_1.gif)";
  document.getElementById("slide2").style.backgroundImage = "url(images/slide_2.gif)";
  document.getElementById("slide3").style.backgroundImage = "url(images/slide_3.gif)";
    switch (time) {
      case 0:
        document.getElementById("slide0").style.backgroundImage = "url(images/slide_0_.gif)";
        break;
      case 20:
        document.getElementById("slide1").style.backgroundImage = "url(images/slide_1_.gif)";
        break;
      case 10:
        document.getElementById("slide2").style.backgroundImage = "url(images/slide_2_.gif)";
        break;
      case 5:
        document.getElementById("slide3").style.backgroundImage = "url(images/slide_3_.gif)";
        break;
    }
    if (!GlobalSlideShow) {
      var links = document.getElementsByTagName("A");
      GlovalSlideShowImages = new Array();
        for (var i = 0; i < links.length; i++) {
            if (links[i].rel == "lightbox[girls_"+GlobalSlideShowResolution+"]") {
              GlovalSlideShowImages[GlovalSlideShowImages.length] = links[i];
            }
        }
      GlobalSlideShow = true;
      GlobalSlideShowImageIdx = activeImage;
      GlobalSlideShowTimerId = window.setInterval(continueShow, GlobalSlideShowTimeOut);
    }
    else {
      window.clearInterval(GlobalSlideShowTimerId);
      GlobalSlideShowTimerId = window.setInterval(continueShow, GlobalSlideShowTimeOut);
    }
}







//////////////////////////////////////////////////////////////////
// consts
var RS_UNINITIALIZED = 0;
var RS_LOADING = 1;
var RS_LOADED = 2;
var RS_INTERACTIVE = 3;
var RS_COMPLETE = 4;

var HTTP_STATUS_OK = 200;

var ERROR_INIT = 1000;
var ERROR_BUSY = 1001;
var ERROR_LOAD = 1002;
var ERROR_OPEN_URL = 1003;
var ERROR_OBJECT = 1010;
var ERROR_PROPERTY = 1100;

var RT_UNINITIALIZED = 0;
var RT_SYNC = 1;
var RT_ASYNC = 2;

var CLIENT_REQUEST_TIMEOUT = 300000;

var CT_JSON  = "text/json";
var CT_TEXT  = "text/plain";
var CT_XML  = "text/xml";

var IS_OPERA = navigator.userAgent.indexOf('Opera') != -1;

//////////////////////////////////////////////////////////////////
// classes

function formatClientError (message, code) {
  var e = new Error (code);
  e.description = message;
  e.name = "HTTP Client Error";
  e.code = code;
  return e;
};

// aXmlHttpRequest

function aXmlHttpRequest (url_, method_) {
  // The URL the request is sent to
  this.url = url_ ? url_ : '';

  // Request body (only for POST requests)
  this.body = '';

  // Type of request (async / sync)
  this.type = RT_UNINITIALIZED;

  // Instance of XMLHttpRequest
  this.xmlhttp = null;

  // Timeout in milliseconds for requests
  this.timeout = CLIENT_REQUEST_TIMEOUT;

  // Content-type for Request
  this.contentType = CT_TEXT;

  // HTTP request method (POST/GET)
  this.method = (method_? method_ : "GET");

  // result format
  this.resultFormat = "json"; // 'json' - text or 'xml' - XML document
}

aXmlHttpRequest.prototype.reset = function() {
  this.url = '';
  this.body = '';
  this.type = RT_UNINITIALIZED;
  this.xmlhttp = null;
  this.timeout = CLIENT_REQUEST_TIMEOUT;
};

aXmlHttpRequest.prototype.prepare = function(xmlhttp) {
  this.xmlhttp = xmlhttp;

  switch (this.type) {
    case RT_ASYNC:
      try {
        this.xmlhttp.open (this.method, this.url, true);
      }
      catch (e) {
        throw formatClientError ("Error open url: " + this.url, ERROR_OPEN_URL);
      };
      break;
    case RT_SYNC:
      try {
        this.xmlhttp.open (this.method, this.url, false);
      }
      catch (e) {
        throw formatClientError ("Error open url: " + this.url, ERROR_OPEN_URL);
      };
      break;
    default:
      throw formatClientError('Call type invalid ' + this.type,  ERROR_PROPERTY);
      break;
  }

};

aXmlHttpRequest.prototype.send = function() {
  var data = this.body;
    if (this.method && (this.method.toUpperCase() == "GET"))
      data = null;
  var length = 0;
    if ( data != null && data != undefined)
      length = data.length;
    else
      data = '';

  this.xmlhttp.setRequestHeader ('Accept-Charset', 'UTF-8');

    if (this.method.toUpperCase() == "POST")  {
      this.xmlhttp.setRequestHeader ('Content-Type', 'multipart/form-data"');
      this.xmlhttp.setRequestHeader ('Enctype', 'multipart/form-data"');
    }

  this.xmlhttp.setRequestHeader ('Content-Length', length);
  this.xmlhttp.send (data);
};

//////////////////////////////////////////////////////////////////////////////
//
// aXmlHttpClient

function aXmlHttpClient (url) {
  // XMLHttpRequest Object
  this.xmlhttp = null;
  // The object that contains the async callback methods
  this.userhandler = null;

  // Defaulr request url
  this.defaulturl = url ? url : '';

  // Id used for timing out async calls
  this.timeout_id = null;
  // Logger
  this.logger = null;
}

aXmlHttpClient.prototype.init = function() {
  try {
    this.xmlhttp = new XMLHttpRequest();
  }
  catch (e) {
    var MSXML_XMLHTTP_PROGIDS = new Array('MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP');
    var success = false;
      for ( var i = 0; i < MSXML_XMLHTTP_PROGIDS.length && !success; i++ ) {
        try {
          this.xmlhttp = new ActiveXObject(MSXML_XMLHTTP_PROGIDS[i]);
          success = true;
        }
        catch (e) {}
      }
      if ( !success )
        throw formatClientError ('Unable to create XMLHttpRequest.', ERROR_INIT);
  }
};


// Perform an synchronous call (results returned directly)
aXmlHttpClient.prototype.call = function (request) {
    if ( !this.xmlhttp ) this.init ();
    if ( this.callInProgress () ) throw formatClientError ('Call in progress', ERROR_BUSY);

    if (!request) request = new aXmlHttpRequest (this.defaulturl);
  this.userhandler = null;

  request.type = RT_SYNC;
  request.prepare (this.xmlhttp);
  request.send ();

    if ( this.xmlhttp.status == HTTP_STATUS_OK ) {
        if (request.resultFormat == 'xml') return this.xmlhttp.responseXML;
      return this.xmlhttp.responseText;
    }
    else {
      var errorMsg = '[HTTP Status: ' + this.xmlhttp.status + '] ' + this.xmlhttp.statusText;
      var err = formatClientError (errorMsg, ERROR_LOAD);
      err.headers = this.xmlhttp.getAllResponseHeaders ();
      throw err;
    }
};

// Perform an asynchronous call (results sent to handler)
aXmlHttpClient.prototype.callAsync = function (request, handler) {
    if ( !this.xmlhttp ) this.init ();
    if ( this.callInProgress () ) throw formatClientError ('Call in progress', ERROR_BUSY);

    if (!request) request = new aXmlHttpRequest (this.defaulturl);
    if (handler != undefined && handler != null) this.userhandler = handler;
    else this.userhandler = null;

  request.type = RT_ASYNC;

  var self = this;
  var req = request;
  this.xmlhttp.onreadystatechange = function() {
    self.stateChangeCallback (self, req);
  }
  request.prepare (this.xmlhttp);
  request.send ();

  this.timeout_id = window.setTimeout (
                          function() {
                            self.abort (self);
                          },
                          request.timeout);
};

// Checks to see if XmlHttpRequest is busy
aXmlHttpClient.prototype.callInProgress = function () {
    if ( !this.xmlhttp ) return false;
    if ( this.xmlhttp.readyState == RS_UNINITIALIZED || this.xmlhttp.readyState == RS_COMPLETE ) return false;
  return true;
};

// Aborts the request
aXmlHttpClient.prototype.abort = function (client)  {
  if (!client) client = this;
  if ( client.callInProgress () ) {
    client.xmlhttp.abort ();
    var errorMsg = 'Operation aborted';
      if (this.logger) this.logger.debug ( errorMsg );
      if (client.userhandler != null && typeof(client.userhandler) == 'function')  {
        client.userhandler (null);
      };
  }
};


// Callback for asyncCalls

aXmlHttpClient.prototype.stateChangeCallback = function (client, request) {
  switch (client.xmlhttp.readyState) {
    // XMLHTTPRequest.open() has just been called
    case RS_LOADING:
      if (this.logger)
        this.logger.debug ( request.url + ': loading.' );
      break;
    // XMLHTTPRequest.send() has just been called
    case RS_LOADED:
      if (this.logger)
        this.logger.debug ( request.url + ': sent.' );
      break;

    // Fetching response from server in progress
    case RS_INTERACTIVE:
      break;

    // Download complete
    case RS_COMPLETE:
      window.clearTimeout (client.timeout_id);

      switch (client.xmlhttp.status) {
        case HTTP_STATUS_OK:
          if (client.userhandler != null &&
            typeof(client.userhandler) == 'function')  {
            var res = (request.resultFormat == 'xml' ? client.xmlhttp.responseXML : client.xmlhttp.responseText);
            client.userhandler (res);

          } else if (this.logger)
            this.logger.debug ( request.url + ': completed.' );
          break;

        // Special case for IE on aborted requests
        case 0:
        // Do nothing
          break;

        default:
          var statusText = client.xmlhttp.statusText;
          if (statusText != undefined)
            statusText = " " + statusText;
          else
            statusText = "";
          var e = formatClientError (
              'HTTP Error: [' + client.xmlhttp.status + ']' + statusText,  ERROR_LOAD);
          e.headers = this.xmlhttp.getAllResponseHeaders ();
          if ( this.logger ) {
            this.logger.error (request.url + ': error retrieving data.', e);
          } else if (client.userhandler != null &&  typeof(client.userhandler) == 'function')  {
            client.userhandler (client.xmlhttp.responseText);
          }
          break;
      }
      break;
  }

};




function fixEvent(e) {
    if (typeof e == 'undefined') e = window.event;
    if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
    if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
    if (!e.srcElement) e.srcElement = e.target;
  return e;
}

function emailinputstart (inp) {
  inp.value = inp.value == "  Your Email" ? "" : inp.value;
  inp.style.color = inp.value == "  Your Email" ? "#666666" : inp.style.color;
  document.body.onmousedown = function (e) {
    e = fixEvent(e);
      if (inp != e.srcElement || e.srcElement.id != "emailSubmit") {
        inp.value = inp.value.length == 0 ? "  Your Email" : inp.value;
        inp.style.color = inp.value == "  Your Email" ? "#666666" : inp.style.color;
        document.body.onmousedown = null;
      }
  }
}

function emailinputprocess (inp) {
  inp.style.color = validateEmail(inp.value) ? "#000000" : "#555555";
}

function validateEmail (email) {
  var r = new RegExp("^['\\w_-]+(\\.['\\w_-]+)*@['\\w_-]+(\\.['\\w_-]+)*\\.[a-zA-Z]{2,4}$");
  return r.test(email);
}

function subscribe () {
  document.getElementById("emailSubmit").disabled = true;
  var inp = document.getElementById("emailInput");
    if (!validateEmail(inp.value)) {
      alert("Wrong email specified.");
      return;
    }
  var data = sendRequest("subscribe.php", inp.value);
  alert(data);
    if (data == "Thank you.") {
      //window.location.reload();
    }
  document.getElementById("emailSubmit").disabled = false;
}