var redirectLocation = null;
var popup = null; //popup window with question
var popup_y = 0;
// size of window
var pwWidth = 200;
var pwHight = 135;
// cookie name
var cookieName = 'UserMail_';
var _churchId = '';
var _isMember = '';

function getMedia(mediaId, mediaType, chrId, isMember) {
	_mediaId = mediaId;
	_churchId = chrId;
	_isMember = isMember;
	// set redirectLocation
	redirectLocation = 'getmedia.php?mediaid=' + mediaId + '&mediatype=' + mediaType;
	cookieName += chrId;
	if (isMember) {
		//alert('DEBUG: already member');
		var artwin=open("","church");
		artwin.document.location = redirectLocation;
	} else {
		window.onscroll = onScrollHnd;
		showQuestion(mediaType, mediaId);
	}
}

function onScrollHnd() {
	// change window location
	//alert(document.documentElement.scrollTop);
	//alert(document..scrollTop);
	var s = popup.style;
	wh = windowWidthHeight();
 	s.left =  (wh[0] - pwWidth) / 2 + 'px';
	s.top = (wh[1] - pwHight) / 2 + document.body.scrollTop + 'px';
}

// show popup with question
function showQuestion(mediaType, mediaId) {
  if 	(popup) return;
  sendStatus();
 // Create popup window with question
  popup = createPopupDiv();
	
  // YES link
  lnkYes = document.createElement('a');
  lnkYes.appendChild(document.createTextNode('[YES]'));
  lnkYes.href = "javascript:on_yesClick()";
  popup.appendChild(lnkYes);
  popup.appendChild(document.createTextNode('     '));
  // NO link
  lnkNo = document.createElement('a');
  lnkNo.appendChild(document.createTextNode('[NO]'));
  lnkNo.href = "javascript:on_noClick()";
  popup.appendChild(lnkNo);
  popup.appendChild( document.createElement('HR'));

	if (!_isMember) {
		getMbr = document.createElement('a');
		getMbr.appendChild(document.createTextNode('Get a Sermon Connect pass'));
		getMbr.href = "pcontroler.php?p=addmembership&client_id=" + _churchId;
		popup.appendChild(getMbr);
		popup.appendChild( document.createElement('HR'));
  }
  // make div visible...
  //var parentDiv = document.getElementById("msg"); 
  var parentDiv = document.getElementsByTagName("body")[0];
  parentDiv.appendChild(popup);
}

//=================================================================================
// Popup window handlers
function on_yesClick() {
  document.location = redirectLocation;
}

function on_noClick() {
	// already created
	if (document.getElementById("email")) return; 
  // If we already got user email
  if (getCookie(cookieName)) {
    //alert('DEBUG:We already have this users email');
    document.location = redirectLocation;
    return;
  }

  //create email reuest page
  popup.appendChild(document.createTextNode('Please, enter your email'));
  popup.appendChild(document.createElement('br'));
  var inp = document.createElement('input');
  inp.id = 'email';
  popup.appendChild(inp);
  popup.appendChild(document.createElement('br'));
  // create button
  btn = document.createElement('input');
  btn.value = 'Save email';
  btn.type = 'button';
  btn.onclick = on_btnClick; 
  popup.appendChild(btn);
}

function on_btnClick () {
  // validate eamil address
  var mail = document.getElementById("email").value;
  var regexp = /^[\w\.=-]+@[\w\.-]+\.[\w\.-]{2,4}$/;
  if (!regexp.test(mail)) {
    alert('Email has wrong format!\nPlease inpute valid email adress.');
    return;
  }
  // save to cookie
  var today = new Date();
  var expire = new Date();
  expire.setTime(today.getTime() + 3600000*24*365);
  document.cookie = cookieName + "=" + mail + ";expires=" + expire.toGMTString();
  // redirect to get media page
  document.location = redirectLocation;
}

function on_closeClick() {
	parentDiv = document.getElementsByTagName("body")[0];
	parentDiv.removeChild(popup);
	popup = null; //popup window with question
 	popup_y = 0;
}

function sendStatus() {
	r = createRequest();
	var sURL = "functions/fvisitorstat.php?client_id=" + _churchId + "&mi=" + _mediaId;
	r.open( "GET", sURL, false );
	r.send("");
}	

// Popup window handlers END
//=================================================================================




function createPopupDiv() {
 
 var dv = document.createElement('div');
 var s = dv.style;
 s.display = 'block';
 //s.position = 'fixed';
 s.position = 'absolute';
 // Get wind size
 wh = windowWidthHeight();
 //alert(wh);
 s.left =  (wh[0] - pwWidth) / 2 + 'px';
 s.top = (wh[1] - pwHight) / 2 + document.body.scrollTop + 'px';
 s.textAlign ='center';
 s.border = 'solid blue 3px';
 s.padding = '0px'; 
 //s.padding = '10px';
 //s.paddingTop = '0px';

 s.backgroundColor = 'rgb(255,255,225)';
 s.width =  pwWidth + 'px';
 s.hight =  pwHight + 'px';
 s.zindex = '100';
 
 	tableDv = document.createElement('div')
	tableDv.innerHTML = '<table width=100%  height=5 border=0 CELLPADDING=0 BGCOLOR=blue> <tr>' +
		'<td  align=center width=95% style="color: white;">Are you first time visitor?</td>' +
		'<td width=5%><input name=Close type=button value=X onClick=javascript:on_closeClick()>' +
		'</td></tr></table>';
	//tableDv.appendChild(document.createTextNode('Text in DIV'));
	dv.appendChild(tableDv);
  dv.appendChild( document.createElement('HR'));

 return dv;
}

function getCookie(c_name) {
  if (document.cookie.length>0)   {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1) { 
     c_start=c_start + c_name.length+1 
     c_end=document.cookie.indexOf(";",c_start)
     if (c_end==-1) c_end=document.cookie.length
      return unescape(document.cookie.substring(c_start,c_end))
     } 
    }
  return null
}

