/* $Id: op-global.js 20072 2010-10-06 16:59:42Z asukhotin $ */


(function( $ ){
  
 function EmailPopup(el, content) {
    this.input = $(el);
    this.popupContent = '';
    this.init();
    this.hide();
  };

  EmailPopup.prototype = {
    init: function() {
      var that = this;      

      this.emailregex = /^[\w\d\_\-\.]+@[\w\d\_\-\.]+\.[\w\d\_\-\.]+/;
      this.emailmsg = "Please enter correct email address";
      this.popupContent = $('<div></div>');
      
      var btnClose = $('<a href="#" id="btn-close">x</a>');

      btnClose.click(function(){that.popupPanel.fadeOut();});
      
      $('<h3 id="popup-header">Email this page</h3>').appendTo(this.popupContent);
      
      this.divCform = $('<div id="cform"></div>');
      
      var tform = $('<form method="POST" action="/lib/captcha/check.php"></form>');
      
      var lblTo = $('<label>To:</label>');
      tform.append(lblTo);

      this.inputTo = $('<input id="mailto" name="mailto" type="text" value="" />');
      tform.append(this.inputTo);

      this.toErr = $('<div id="mailtoerr"></div>');
      tform.append(this.toErr);

      var lblFrom = $('<label>From:</label>');
      tform.append(lblFrom);

      this.inputFrom = $('<input id="mailfrom" name="mailfrom" type="text" value="" />');
      tform.append(this.inputFrom);

      this.fromErr = $('<div id="mailfromerr"></div>');
      tform.append(this.fromErr);

      var lblMessage = $('<label>Message:</label>');
      tform.append(lblMessage);

      this.inputMessage = $('<textarea id="message" name="message">I thought you may find this link of interest</textarea>');
      tform.append(this.inputMessage);

      this.imgCaptcha = $('<img id="cimg" />');
      

      tform.append(this.imgCaptcha);

      this.errMsg = $('<div id="errormsg"></div>');
      tform.append(this.errMsg);

      var lblCaptcha = $('<label id="lblcode">Enter the code shown in the image:</label>');
      tform.append(lblCaptcha);

      this.inputCode =  $('<input id="code" type="text" name="code" autocomplete="off" />');
      tform.append(this.inputCode);

      this.errCode = $('<div id="codeerr"></div>');
      tform.append(this.errCode);

      this.btnEmail = $('<input type="submit" value="Email" class="btn" id="btn-email" />');
      this.btnEmail.click(function(e) { e.preventDefault(); that.send(); });
      tform.append(this.btnEmail);

      this.imgLoading = $('<img src="/images/nav/loading.gif" alt="Sending..." id="loading-indicator" />');
      tform.append(this.imgLoading);
      this.imgLoading.hide();
      
      this.divCform.append(tform);
      
      this.divCmsg = $('<div id="cmsg" style="display:none"></div>');
        
      this.popupContent.append(this.divCform, this.divCmsg);
        
        
      this.popupPanel = this.rootLayers = $('<div id="emailpopup" class="emailpopup"></div>').append(btnClose, this.popupContent)
      .css({ 
        display: "none", 
        position: "absolute", 
        zIndex: 100
      });

      this.popupPanel.appendTo(document.body);
      this.input.click(function(){ that.show(); });
    },
    
    cimgurl: function() {
      var t = new Date();
      var nurl = '/lib/captcha/securimage_show.php?sid='+t.getTime();
      return nurl;
    },
    
    send: function() {
      var that = this;
      var formOk = false;
      var firstCheck = true;


      formOk = this.CheckField('mailfrom', this.emailregex, 'mailfromerr', '', this.emailmsg);
      formOk &= this.CheckField('mailto', this.emailregex, 'mailtoerr', '', this.emailmsg);

      if (formOk) {
      
        that.btnEmail.hide();
        that.imgLoading.show();
        
        $.ajax({
          type: 'POST',
          url: '/lib/captcha/check.php',
          data: {
            code: that.inputCode.val(),
            from: that.inputFrom.val(),
            to:   that.inputTo.val(),
            d:    data,
            version: 2,
            msg:  that.inputMessage.val()
          },
          success: function(data) {
            try {
              eval(data);
            } catch(ex) { }

            if (captchaResult) {
              if (captchaResult.valid) {
                that.divCform.hide();
                that.divCmsg.show();
                that.divCmsg.html('Thank you! Your message has been sent to ' + captchaResult.to);
                that.popupPanel.delay(1000).fadeOut();
              } else {
                that.initForm();
              }
            }	

          },
          error: function(req, status, error) {
            console.log('error:'+status);
          },
          
          dataType: 'text'
          
        });

      }
    },

    CheckField: function(id,regex,errid,matchmsg,nomatchmsg) {
      var field = $('#' + id, this.popupContent);
      var error = $('#' + errid, this.popupContent);
      var rc = true;
      if (field) {
        if (error && field.val().match(regex)) {
          error.html(matchmsg);
          rc = true;
          field.removeClass('fielderror');
        } else {
          error.html(nomatchmsg);
          rc = false;
          field.addClass('fielderror');
        }
      }
      return rc;
    },

    initForm: function() {
      this.imgLoading.hide();
      this.btnEmail.show();
      this.inputCode.val('');
      this.imgCaptcha.attr('src', this.cimgurl());
    },

    show: function() {
      this.initForm();
      this.divCform.show();
      this.divCmsg.hide();
      this.setPosition();
      this.rootLayers.css("display", "block");
      this.input.unbind("focus", this.show);
    },

    hide: function() {
      this.rootLayers.css("display", "none");
      this.input.focus(this.show);
    },

    setPosition: function() {
      this.rootLayers.css({
        top: ( $(window).height() - this.popupPanel.outerHeight() ) / 2+$(window).scrollTop() + "px",
        left: ( $(window).width() - this.popupPanel.outerWidth() ) / 2+$(window).scrollLeft() + "px"
      });
    }

  };

  $.fn.emailthis = function(content) {
    return this.each(function() { 
      new EmailPopup(this, content); 
    });
  };  
  
})( jQuery );

function NewWindow(url,width,height) {
 var w = window.open(url,'','scrollbars=no,menubar=no,height='+height+',width='+width+',resizable=yes,toolbar=no,location=no,status=no');
}

function NewNamedWindow(url,width,height,title) {
 NewGenericWindow(url,width,height,title,null);
}

function NewGenericWindow(url,width,height,title,options) {
 var defaultOptions = {
	scrollbars: "no",
	menubar: "no",
	height: 0,
	width: 0,
	resizable: "yes",
	toolbar: "no",
	location: "no",
	status: "no"
 };

 defaultOptions.width=width;
 defaultOptions.height=height;

 var windowOptions = '';

 if (options) {
	 for (var i in defaultOptions) {
		if (options[i]) defaultOptions[i] = options[i];
		windowOptions += i+'='+defaultOptions[i]+',';
	 }
 }

 var w = window.open(url,'',windowOptions);
}

function jumpto(x){
if (x != "") {
    window.open(x);
    return false;
    }
}

function cleartext(ele){
ele.value="";
ele.focus();
}

function addLoadEvent(func) {
  $().ready(function() {
    func();
  });
}


(function( $ ){

$().ready(function(){

  var urlRegex = /^http:\/\/((www.orgplus.co.uk|uk8.webtest2.orgplus.com)\/?(|index.htm)?$|(live|dev).sf.orgplus.com|(www.|)(humanconcepts|orgplus).com\/(reg02|servlets))/;

  if (window.location.href.search(urlRegex) ) {
  
    if ($('#content').html()) {

      var linkEmailPage = $('<a id="cmd-email-page" href="#">E-mail</a>').emailthis();
      var linkPrintPage = $('<a id="cmd-print-page" href="?mode=print" target="_blank">Print</a>');

      var divToolbar = $('#toolbar');
      
      if (!divToolbar.size()) {
        divToolbar = $('<div id="toolbar"></div>');
        divToolbar.append(linkEmailPage);
        divToolbar.append(linkPrintPage);
        if ($('#content:first-child').html()) {
          divToolbar.insertBefore($('#content:first-child'));
        } else {
          $('#content').append(divToolbar);
        }
      } else if (!$(':first-child', divToolbar).html()) {
        divToolbar.append(linkEmailPage);
        divToolbar.append(linkPrintPage);
      }
    
   }
  }
});

})( jQuery );
