/**
 * Functions and classes for picture contests section
 * 
 * @author Erick S <esatire at gmail (do not spam you bastards!) com >
 * @version 1.0.1
 * @copyright Atarim Group LTD.
 */

/**
 * 'Namespace' for all contest related functions
 */
function PicsContest() {}

/** Holds commonly accessed DOM elements */
PicsContest.voteBox = null;
PicsContest.voteBoxOffset = null;
PicsContest.voteBoxCover = null;
PicsContest.voteBoxTitle = null;
PicsContest.voteBoxImages = null;
PicsContest.request = null;

PicsContest.contestId = null;
PicsContest.pickedAlbum = null;

PicsContest.ORG_TEXT = 'הצביעו:';
PicsContest.VOTING_TEXT = 'שולח הצבעה...';
PicsContest.VOTED_TEXT = 'ההצבעה התקבלה';

PicsContest.lightStars = function(evt)
{
	var pos = getEventPos(evt);
	pos.x = Math.ceil((pos.x-PicsContest.voteBoxOffset.x)/10) * 10;
	if (pos.x > 100) pos.x = 100;
	PicsContest.voteBoxCover.style.width = pos.x + 'px';
}

PicsContest.vote = function(evt)
{
	var pos = getEventPos(evt);
	var voteValue = Math.ceil((pos.x-PicsContest.voteBoxOffset.x)/10);
	if (voteValue > 10) voteValue = 10;
	else if (voteValue == 0) return;

	var postInfo = 'vote=' + voteValue;
	PicsContest.request.Post(window.location,postInfo,PicsContest.voteResult);
	PicsContest.voteBoxTitle.innerHTML = PicsContest.VOTING_TEXT;
	PicsContest.voteBox.onmousemove = null;
	PicsContest.voteBox.onclick = null;
	PicsContest.voteBox.style.cursor = 'auto';
}

PicsContest.voteResult = function(responseText)
{
	try
	{
		if (responseText.length == 0) throw Error('לא התקבלה תגובה מהשרת');
		var result = eval('({'+responseText+'});');
		if (result.error != null) throw Error(result.error);
		
		$('votersCount').innerHTML = result.voters;
		$('ratingBar').style.width = (Math.floor(result.avg * 6)) + 'px';
		PicsContest.voteBoxTitle.innerHTML = PicsContest.VOTED_TEXT;
		//if (result.showPopup == 1) Castro.requestPopup('voter');
	}
	catch (ex)
	{
		if (ex.message == 'not_logged')
		{
			window.location = 'contest.php?m=login';
		}
		else
		{
			PicsContest.requestOnError(ex.message);
		}
	}
}

PicsContest.requestOnError = function(errorText)
{
	MessageBox.alert(errorText);
	PicsContest.voteBoxTitle.innerHTML = PicsContest.ORG_TEXT;
	PicsContest.voteBox.onmousemove = PicsContest.lightStars;
	PicsContest.voteBox.onclick = PicsContest.vote;
	PicsContest.voteBox.style.cursor = 'pointer';
}

PicsContest.initPhotoPage = function(numPerPage)
{
	CommentNavigator.prototype = new PageNavigator;
	commentNavigator = new CommentNavigator('comments', numPerPage, 2);

	commentNavigator.secondNavigator = $('topNavigator');
	setTimeout("commentNavigator.requestPage(0)",150);
	window.onbeforeunload = clearRequests;
	
	// Init vote box, if present
	PicsContest.voteBox = $('voteBox');
	if (PicsContest.voteBox != null)
	{
		PicsContest.voteBoxOffset = getRealOffset(PicsContest.voteBox);
		PicsContest.voteBox.onmousemove = PicsContest.lightStars;
		PicsContest.voteBox.onclick = PicsContest.vote;
		PicsContest.voteBox.style.cursor = 'pointer';

		PicsContest.voteBoxCover = $('voteBoxCover');
		PicsContest.voteBoxTitle = $('voteBoxTitle');
				
		PicsContest.voteBoxImages = PicsContest.voteBox.getElementsByTagName('img');
		PicsContest.request = new XHR(20000);
		PicsContest.request.SetErrorFunc(PicsContest.requestOnError);
	}
}

PicsContest.removePic = function()
{
	if (PicsContest.request == null)
	{
		PicsContest.request = new XHR(20000);
		PicsContest.request.SetErrorFunc(PicsContest.requestOnError);		
	}
	if (PicsContest.request.InProgress())
	{
		MessageBox.alert('פעולה קודמת עדיין לא הסתיימה. המתינו מספר שניות ונסו שנית.')
		return;
	}
	MessageBox.confirm('לא ניתן להשיב תמונה לתחרות לאחר ההסרה.<br />האם להסיר?',PicsContest.removePicConfirm)
}
PicsContest.removePicConfirm = function()
{
	var postInfo = 'remPic=1';
	PicsContest.request.Post(window.location,postInfo,PicsContest.removePicResult)
}
PicsContest.removePicResult = function(responseText)
{
	if (responseText != 'ok')
	{
		MessageBox.alert(responseText);
		return;
	}
	var element = $('removePicLink');
	element.onclick = null;
	element.style.cursor = 'auto';
	element.innerHTML = 'התמונה הוסרה מהתחרות בהצלחה'; 
}

PicsContest.pickAlbumPic = function(evt)
{
	var element = getEventTarget(evt);
	if (!element.id || element.tagName.toUpperCase() != 'IMG') return;
	//alert('hi!');
	//alert(document.getElementById('agree').checked);
	/*if (document.getElementById('agree').checked!=true) {
		alert('נא לאשר את תקנון המבצע');
		return;
	} else*/
		agree = '1';
	
	data = {contestId: PicsContest.contestId, albumId: PicsContest.pickedAlbum, picId: element.id}
	var postInfo = 'pickImage=1&agree='+agree+'&contest=' + data.contestId + '&album=' + data.albumId + '&pic='+data.picId;
	PicsContest.request.Post(window.location,postInfo,PicsContest.pickPicResult,data);
}
PicsContest.pickPicResult = function(responseText,data)
{
	try
	{
		var result = eval('({'+responseText+'});');
		if (result.error) throw Error(result.error);
		if (!result.ok || result.ok != 1) throw Error('שגיאה לא ידועה בבחירת תמונה');
		// Went ok - go to page
		window.location = '/contest.php?id='+data.contestId+'&a='+data.albumId+'&pid='+data.picId;
	}
	catch (ex)
	{
		MessageBox.alert(ex.message);
	}
}

PicsContest.getUserAlbumPics = function(selectElement)
{
	var value = selectElement.options[selectElement.selectedIndex].value;
	if (value == 0)
	{
		$('albumPics').innerHTML = '';
		return;
	}
	PicsContest.pickedAlbum = value;
	var postInfo = 'getAlbumPics=1&album=' + value;
	PicsContest.request.Post(window.location,postInfo,PicsContest.getUserAlbumPicsResult);
}

PicsContest.getUserAlbumPicsResult = function(responseText)
{
	try
	{
		if (!responseText) throw Error('No response!');
		var result = eval('({'+responseText+'});');
		if (result.error) throw Error(result.error);
		var html = new Array();
		if (!result.pics) throw Error('שגיאה במידע על התמונות');
		if (result.pics.length == 0)
		{
			$('albumPics').innerHTML = 'אין תמונות באלבום זה';
		}
		else
		{
			for (var i=0;i<result.pics.length;i++)
				html.push('<div><img id="'+result.pics[i][0]+'" src="'+result.prefix+result.pics[i][1]+'"></div>');
				$('albumPics').innerHTML = html.join(' ');
		}
	}
	catch (ex)
	{
		MessageBox.alert(ex.message);
	}
}

/* For castro contest */
Castro.popup = null;
Castro.request = null;

function Castro(){}

Castro.mailRegexp = /^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$/;
Castro.phoneRegexp = /^[0-9]{2,3}-?[0-9]{7}/

Castro.fillDetailsFormCheck = function(theform) {
	var form = document.forms['castroDetails'];
	var fname = trim(form.elements['fname'].value);
	var lname = trim(form.elements['lname'].value);
	var email = trim(form.elements['email'].value);
	var phone = trim(form.elements['phone'].value);
	// Validation
	try
	{
		if (fname.length == 0 || lname.length == 0) throw Error('יש למלא שם ושם משפחה');
		if (!Castro.mailRegexp.test(email)) throw Error('האי-מייל שהוכנס איננו תקין');
		if (!Castro.phoneRegexp.test(phone)) throw Error('הטלפון שהוכנס איננו תקין');
		return true;
	}
	catch (ex)
	{
		alert(ex.message);
		return false;
	}
}

/**
* format message according to contest-design
* 
* @param string msgBody
*/
Castro.getFormattedMsg = function(msgBody) {
	var fillDetailsForm = "<div style=\"text-align:right;color:#000;width:669px;height:357px;background:url('/campaigns/static/images/kef/kef_popup_bg.jpg') no-repeat;\">"+
		msgBody+"</div></form>";
	return fillDetailsForm;
}

/**
* popup details update
*
* @param string typeOfSender ('uploader','voter')
**/
Castro.requestPopup = function(typeOfSender)
{	
	if (Castro.request == null) {
		Castro.request = new XHR(20000);
	}
	
	//return true; /*
	/*if(num == 1) {
		Castro.popup = new StaticPopup();
		Castro.popup.setContent('this is one');
		Castro.popup.okButton.value = 'סגור';
		Castro.popup.showCenter(StaticPopup.BUTTON_OK);
	} else {*/
	
	if (Castro.popup) {
		Castro.popup.showCenter(StaticPopup.BUTTON_OK);
	} else {
		var msgPrelude; // prelude the form
		if(typeOfSender == 'uploader')
			msgPrelude = "אם אתה תהיה הפרזנטור הבא של כיף, מישהו יצטרך לספר לך על זה... <br />מלא את פרטיך כדי שנוכל ליצור איתך קשר:";
		else 
			msgPrelude = "תודה שדרגתם! עכשיו רק מלאו את פרטיכם ותוכלו לזכות במוצרי כיף";
		
		var fillDetailsForm = "<form method='post' action='' name='castroDetails'>"+
			Castro.getFormattedMsg("<input type='hidden' name='typeOfSender' value='"+typeOfSender+"' />"+
			"<table border='0' style='margin-top:95px;width:280px;margin-right:72px;color:#555 !important;'>"+
			"<tr><td colspan='2'>"+msgPrelude+"<br /><br /></td></tr>"+
			"<tr>"+
			"	<td>שם פרטי</td>"+
			"	<td>שם משפחה</td>"+
			"</tr><tr>"+
			"	<td><input type='text' name='fname' value='' size='15' /></td>"+
			"	<td><input type='text' name='lname' value='' size='15' /></td>"+
			"</tr><tr>"+
			"	<td colspan='2'>דואל: <input type='text' name='email' value='' size='30' /></td>"+
			"</tr><tr>"+
			"	<td colspan='2'>טלפון: <input type='text' name='phone' value='' size='12' /></td>"+
			"</tr><tr>"+
			"	<td colspan='2'>איך שמעת על התחרות?</td>"+
			"</tr><tr>"+
			"	<td colspan='2'><select name='referred_from' style='font-size:9pt;font-family:Tahoma,Arial;color:#555555;'>"+
			"<option value='newspaper'>קראתי בראש1</option><option value='internet'>ראיתי באינטרנט</option>"+
			"<option value='friend'>שמעתי מהחבר'ה</option><option value=''>וואלה, לא זוכר</option></select></td>"+
			"</tr>"+
			"</table>") + "</form>";
		/*var fillDetailsForm = "<form method='post' action='' name='castroDetails'>"+
			"<div style=\"text-align:right;color:#000;width:669px;height:357px;background:url('/campaigns/static/images/kef/kef_popup_bg.jpg') no-repeat;\">"+
			"<input type='hidden' name='typeOfSender' value='"+typeOfSender+"' />"+
			"<table border='0' style='margin-top:95px;width:280px;margin-right:72px;color:#000;'>"+
			"<tr><td colspan='2'>"+msgPrelude+"<br /><br /></td></tr>"+
			"<tr>"+
			"	<td>שם פרטי</td>"+
			"	<td>שם משפחה</td>"+
			"</tr><tr>"+
			"	<td><input type='text' name='fname' value='' size='15' /></td>"+
			"	<td><input type='text' name='lname' value='' size='15' /></td>"+
			"</tr><tr>"+
			"	<td colspan='2'>דואל: <input type='text' name='email' value='' size='30' /></td>"+
			"</tr><tr>"+
			"	<td colspan='2'>טלפון: <input type='text' name='phone' value='' size='28' /><br /></td>"+
			"</tr>"+
			"</table>"+
			"</div></form>";*/
		
		Castro.popup = new StaticPopup();
		Castro.popup.setContent(fillDetailsForm);
		Castro.popup.okButton.value = 'שלח פרטים';
		Castro.popup.onOk = function(data) { // when pressing update button, trigger function to submit form
			var form = document.forms['castroDetails'];
			var fname = trim(form.elements['fname'].value);
			var lname = trim(form.elements['lname'].value);
			var email = trim(form.elements['email'].value);
			var phone = trim(form.elements['phone'].value);
			var referred_from = trim(form.elements['referred_from'].value);
			// Validation
			try
			{
				if (fname.length == 0 || lname.length == 0) throw Error('יש למלא שם ושם משפחה');
				if (!Castro.mailRegexp.test(email)) throw Error('האי-מייל שהוכנס איננו תקין');
				if (!Castro.phoneRegexp.test(phone)) throw Error('הטלפון שהוכנס איננו תקין');
				// Post details
				var details	= 'castroDetails=1&fname=' + encodeURIComponent(fname) +
								'&lname=' + encodeURIComponent(lname) + '&email=' + email +
								'&phone=' + phone + '&contestId=' + PicsContest.contestId +
								'&referred_from=' + encodeURIComponent(referred_from);
				Castro.request.Post('contest.php',details,Castro.sendDetailsResult);
			}
			catch (ex)
			{
				alert(ex.message);
				//Castro.requestPopup(typeOfSender); // try again
			}
		}
		Castro.popup.showCenter(StaticPopup.BUTTON_OK);
	//}
	}
}

Castro.requestPopupResult = function(responseText)
{

}

Castro.requestPopupError = function(errorText)
{
	MessageBox.alert(errorText);
}

/* @@@@deprecated
Castro.sendDetails = function()
{
	var form = document.forms['castroDetails'];
	var fname = trim(form.elements['fname'].value);
	var lname = trim(form.elements['lname'].value);
	var email = trim(form.elements['email'].value);
	var phone = trim(form.elements['phone'].value);
	// Validation
	try
	{
		if (fname.length == 0 || lname.length == 0) throw Error('יש למלא שם ושם משפחה');
		if (!Castro.mailRegexp.test(email)) throw Error('האי-מייל שהוכנס איננו תקין');
		if (!Castro.phoneRegexp.test(phone)) throw Error('הטלפון שהוכנס איננו תקין');
		// Post details
		var details	=	'castroDetails=1&fname=' + encodeURIComponent(fname) +
							'&lname=' + encodeURIComponent(lname) + '&email=' + email +
							'&phone=' + phone;
		Castro.request.Post('contest.php',details,Castro.sendDetailsResult);
	}
	catch (ex)
	{
		alert(ex.message);
	}
}*/

/**
* handle result of sending details
* 
* @param string responseText
**/
Castro.sendDetailsResult = function(responseText)
{
	if (responseText == 'ok')
	{
		Castro.popup = new StaticPopup();
		Castro.popup.setContent(Castro.getFormattedMsg('<table border="0" style="margin-top:95px;width:280px;margin-right:72px;color:#000;"><tr><td>תודה שמילאת את פרטיך!</td></tr></table>'));
		Castro.popup.okButton.value = 'סבבה';
		Castro.popup.showCenter(StaticPopup.BUTTON_OK);
		//alert('תודה שמילאת את פרטיך');
		//Castro.popup.hide();		
	}
	else alert(responseText);
}
