var _xmlHttp = null;
var myURL = "http://" + getHttpHost(document.location.href) + "/";
var _mozilla = 0;

function compareProduct(prodID){
  if(_xmlHttp&&_xmlHttp.readyState!=0){_xmlHttp.abort();}
  _xmlHttp=getXMLHTTP();

  if(_xmlHttp){
  _xmlHttp.open("GET", myURL + 'compare.php?pid=' + prodID,true);
    _xmlHttp.onreadystatechange=function() {
      if(_xmlHttp.readyState==4&&_xmlHttp.responseText) {
        ids = _xmlHttp.responseText.split("&");
        productCompared(ids[0]);
      }
    };
    _xmlHttp.send(null)
  }
}

function productCompared(prodID){
  document.getElementById(prodID + '_compare').style.display = 'none';
  document.getElementById(prodID + '_compared').style.display = 'block';
}


function getXMLHTTP(){
  var A=null;
  try{
    A=new ActiveXObject("Msxml2.XMLHTTP");
  }catch(e){
    try{
      A=new ActiveXObject("Microsoft.XMLHTTP");
    }catch(oc){A=null}
  }
  if(!A && typeof XMLHttpRequest != "undefined") {A=new XMLHttpRequest(); _mozilla = 1;}
  return A;
}

//strip the host from a url
function getHttpHost(url){
  var urlParts = url.split('/');
  return urlParts[2];
}


// mail functions

var mailFormSizeX = 320;
var mailFormSizeY = 200;

function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		scrOfY = window.pageYOffset; scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		scrOfY = document.body.scrollTop; scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		scrOfY = document.documentElement.scrollTop; scrOfX = document.documentElement.scrollLeft;
	}
    return [ scrOfX, scrOfY ];
	//window.alert( 'Horizontal scrolling = ' + scrOfX + '\nVertical scrolling = ' + scrOfY );
}

function displayMailForm(product_id) {
    displayBgBlock();
    displayMailBlock(product_id);
    hideLoadingBlock();
    return false;
}

function hideMailForm() {
    hideMailBlock();
    hideLoadingBlock();
    hideBgBlock();
    return false;
}

function displayBgBlock() {
    if (fB = document.getElementById('form_bg')) {
        size = getFullClientSize();
        fB.style.top = 0;
        fB.style.left = 0;
        fB.style.width = size[0];
        fB.style.height = size[1];
        fB.style.display = 'block';
    }
}

function hideBgBlock() {
    if (fB = document.getElementById('form_bg')) {
        fB.style.display = 'none';
    }
}

function displayMailBlock(product_id) {
    if (mF = document.getElementById('mail_form')) {
        brSize = getVisibleClientSize();
        brScrolled = getScrollXY();
        x=Math.round((brSize[0]+brScrolled[0]-mailFormSizeX)/2);
        y=Math.round((brSize[1]+brScrolled[1]-mailFormSizeY)/2);

        mF.style.left = x;
        mF.style.top = y;
        mF.style.width = mailFormSizeX;
        mF.style.height = mailFormSizeY;

        str = '<form action="#" onSubmit="return initInvitation();" onReset="return hideMailForm();" name="mail_form">';
        str += ' <table cellpadding="5" border="0">';
        str += '<tr><td>Your name:</td><td><input name="sender_name"></td></tr>';
        str += '<tr><td>Your email address</td><td><input name="sender_email"></td></tr>';
        str += '<tr><td>Recipient name:</td><td><input name="recipient_name"></td></tr>';
        str += '<tr><td>Recipient email address:</td><td><input name="recipient_email"></td></tr>';
        str += '<tr valign="top"><td>Message:</td><td><textarea name="message"></textarea></td></tr>';
        if (captchaEnabled) {
            str += '<tr><td>Enter symbols:</td><td><img src="images/captcha/captcha.php" border="1" width="160" height="40" vspace="3"><br><input name="captcha" value="" size="30"></td></tr>';
        }
        str += '<tr><td><input type="submit"></td><td><input type="reset"></td></tr>';
        str += '</table>';
        str += '<div id="id_container"></div>';
        str += '</form>';
        mF.innerHTML = str;

        if (iC = document.getElementById('id_container')) {
            iC.innerHTML = '<input type="hidden" name="product_id" value="' + product_id + '">';
        }

        mF.style.display = 'block';
    }
}

function hideMailBlock () {
    if (mF = document.getElementById('mail_form')) {
        mF.style.display = 'none';
    }
}

function displayLoadingBlock() {
    if (mL = document.getElementById('mail_loading')) {
        mF = document.getElementById('mail_form');
        mL.style.left = mF.style.left;
        mL.style.top = mF.style.top;
        mL.style.width = mailFormSizeX;
        mL.style.height = mailFormSizeY;
        mL.style.display = 'block';
    }
}

function hideLoadingBlock() {
    if (mL = document.getElementById('mail_loading')) {
        mL.style.display = 'none';
    }
}

function getFullClientSize() {
    if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        w = document.documentElement.clientWidth;
        h = document.documentElement.clientHeight;
    } else if (document.body) {
        w = document.body.scrollWidth;
        h = document.body.scrollHeight;
    }
    return [w, h];
}

function getVisibleClientSize() {
    return [document.body.clientWidth, document.body.clientHeight];
}

function initInvitation() {
    f = document.forms['mail_form'];
    sender_name = f.elements['sender_name'].value;
    sender_email = f.elements['sender_email'].value;
    recipient_name = f.elements['recipient_name'].value;
    recipient_email = f.elements['recipient_email'].value;
    message = f.elements['message'].value;
    product_id = f.elements['product_id'].value;
    captcha = (captchaEnabled) ? f.elements['captcha'].value : false;

    if (!checkValue(sender_name, 'not_empty')) {
        alert('Please, enter your name');
        return false;
    }

    if (!checkValue(sender_email, 'email')) {
        alert('Please, enter sender correct email');
        return false;
    }

    if (!checkValue(recipient_name, 'not_empty')) {
        alert('Please, enter recipient name');
        return false;
    }

    if (!checkValue(recipient_email, 'email')) {
        alert('Please, enter recipient correct email');
        return false;
    }

    if (!checkValue(message, 'not_empty')) {
        alert('Please, enter message');
        return false;
    }

    if (captchaEnabled) {
        if (!checkValue(captcha, 'not_empty')) {
            alert('Please, enter symbols on the image');
            return false;
        }
    }

    if (!product_id) {
        alert('Error occured while sending mail. Please, reload a page and try again');
        return false;
    }

    sendInvitation(sender_name, sender_email, recipient_name, recipient_email, message, product_id, captcha);
    return false;
}

function checkValue(value, type) {
    if (type == 'not_empty') {
        if (value == '') {
            return false;
        }
    } else if (type == 'email') {
		pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!pattern.test(value)) {
            return false;
        }
    }
    return true;
}

function sendInvitation(sender_name, sender_email, recipient_name, recipient_email, message, product_id, captcha){
  if(_xmlHttp&&_xmlHttp.readyState!=0){_xmlHttp.abort();}
  _xmlHttp=getXMLHTTP();

  if(_xmlHttp){
      url = 'sendInvitation.php?';
      url += 'sender_name='+encodeURIComponent(sender_name);
      url += '&sender_email='+encodeURIComponent(sender_email);
      url += '&recipient_name='+encodeURIComponent(recipient_name);
      url += '&recipient_email='+encodeURIComponent(recipient_email);
      url += '&message='+encodeURIComponent(message);
      url += '&product_id='+encodeURIComponent(product_id);
      url += (captchaEnabled) ? '&captcha='+encodeURIComponent(captcha) : '';
    _xmlHttp.open("GET", myURL +url,true);
    displayLoadingBlock();
    _xmlHttp.onreadystatechange=function() {
      if(_xmlHttp.readyState==4&&_xmlHttp.responseText) {
        if (_xmlHttp.responseText==1) {
          hideMailForm();
          alert('Mail has been sent');
        } else {
          hideMailForm();
          alert('Mail has not been sent');
        }
      }
    };
    _xmlHttp.send(null)
  }
}
