/**
 * Functions for albums section
 * @author Erick S <esatire at gmail dot com>
 * @copyright Atarim Group LTD.
 * @version 1.0.3 24/04/2008
 */

/** Globals */
var uploaderAlbumId = null,uploaderCookieName = null,uploaderCookieContent = null, uploaderSection=null, uploaderSectionValue=null;
var xhr=null;
var token=null,commentNavigator=null,imagePointer=null,tagListElement=null,picTags=null,inTagMode=false;
var canComplain=true,picReady = 0;

function createImageUploader(cookieName,cookieContent, albumId,section,section_value)
{
	var w = (window.screen.availWidth > 800) ? 860 : 630;
	var h = 550;

	// Setting some namespace vars
	uploaderAlbumId = albumId;
	uploaderCookieName = cookieName;
	uploaderCookieContent = cookieContent;
	uploaderSection = section;
	uploaderSectionValue = section_value;
	
	var iu = new ImageUploaderWriter("ImageUploader",w,h);
	
	iu.activeXControlCodeBase = "packages/imageuploader/ImageUploader5.cab";
	iu.activeXControlVersion = "5,5,6,0";
	iu.activeXControlEnabled = true;

	iu.javaAppletJarFileName = "ImageUploader5.jar";
	iu.javaAppletCodeBase = "packages/imageuploader//";
	iu.javaAppletCached = true;
	iu.javaAppletVersion = "5.5.6.0";
	iu.javaAppletEnabled=true;
	
	/*var iu = new ImageUploaderWriter("ImageUploader",w,h);
	iu.activeXControlCodeBase = "packages/imageuploader/ImageUploader5.cab";
	iu.activeXControlVersion = "5,1,10,0";
	iu.activeXControlEnabled = true;
	iu.javaAppletJarFileName = "ImageUploader5.jar";
	iu.javaAppletCodeBase = "packages/imageuploader//";
	iu.javaAppletCached = true;
	iu.javaAppletVersion = "5.1.10.0";
	iu.javaAppletEnabled=true;*/

	iu.showNonemptyResponse = "off";

	iu.addParam("PaneLayout", "TwoPanes");
	iu.addParam("ShowDebugWindow", "false");
	iu.addParam("AllowRotate", "true");
	iu.addParam("ButtonDeselectAllText","הסר סימון");
	iu.addParam("ButtonSelectAllText","סמן הכל");
	iu.addParam("ButtonSendText","שלח");
	iu.addParam("ButtonStopText","הפסק");
	iu.addParam("FileIsTooLargeText", "הקובץ גדול מדי");
	iu.addParam("ProgressDialogTitleText", "העלאת תמונות");
	iu.addParam("MessageBoxTitleText", "מעלה התמונות");

	iu.addParam("MessageUploadCompleteText", "");
	iu.addParam("MessageUploadCancelledText", "העלאת התמונות הופסקה");
	iu.addParam("MessageUploadFailedText", "העלאת התמונות נכשלה בשל בעיות בחיבור");
	iu.addParam("MessageNoResponseFromServerText", "לא התקבלה תגובה מהשרת. נסו שוב בעוד מספר שניות");
	iu.addParam("ProgressDialogCloseWhenUploadCompletesText", "סגור חלון זה לאחר סיום העלאת הקבצים");
	iu.addParam("ProgressDialogPreparingDataText", "...מכין מידע");
	iu.addParam("ProgressDialogWaitingForRetryText", "...בעיה. מנסה שוב");
	iu.addParam("MegabytesText", "מגהבייטים");
	iu.addParam("KilobytesText", "קילובייטים");
	iu.addParam("SecondsText", "שניות");
	iu.addParam("MinutesText", "דקות");
	iu.addParam("HoursText", "שעות");

	iu.addParam("ProgressDialogSentText", "שולח: [Current] מתוך [Total]");
	iu.addParam("ProgressDialogCancelButtonText", "ביטול");
	iu.addParam("ProgressDialogPreviewThumbnailSize", "128");

	iu.addParam("MessageMaxFileCountExceededText", ".ניתן לבחור רק עד [Limit] קבצים");
	iu.addParam("MessageMaxTotalFileSizeExceededText", ".לא ניתן לבחור את הקובץ מכיוון שניתן לשלוח רק עד [Limit] קילובייטים בבת אחת");
	iu.addParam("MessageMaxFileSizeExceededText", ".לא ניתן לבחור את הקובץ מכיוון שגודלו עולה על  [Limit] קילובייטים");

	iu.addParam("BackgroundColor", "#C3E3F8");

	iu.addParam("FileMask", "*.jpg;*.jpeg;*.jpe;");
	iu.addParam("MaxTotalFileSize", "20428800");
	iu.addParam("CheckFilesBySelectAllButton", "true");
	iu.addParam("ShowDescriptions", "false");
	iu.addParam("FilesPerOnePackageCount", "10");

	iu.addEventListener("BeforeUpload","beforeUpload");
	
	// choose what to do according to given section
	switch (uploaderSection)
	{
		case "events":
			iu.addParam("Action", "events.php?m=pics_add&a="+uploaderAlbumId+"&eid=" + uploaderSectionValue);
			iu.addEventListener('AfterUpload',"afterUploadEvents");
			break;
		default:
			iu.addParam("Action", "pics.php?a=" + uploaderAlbumId);
			iu.addEventListener('AfterUpload',"afterUploadAlbums");
			break;
	}
	
	var hostName = window.location.hostname; 
	// Shin1
	if (hostName.match(/^(www.)?shin1.co.il$/i)) 
		iu.addParam("LicenseKey", "71050-10000-0B697-79ECA-7192F;72050-10000-93CAB-567ED-E16B5");
	else// Test
		iu.addParam("LicenseKey", "71050-10000-66318-505B9-178A3;72050-10000-9856E-817C8-B9635");

	iu.writeHtml();
}

function beforeUpload()
{
	getImageUploader("ImageUploader").AddCookie(uploaderCookieName+'='+uploaderCookieContent);
}

function afterUploadAlbums(html)
{
	url = 'pics.php?a='+uploaderAlbumId;
	afterUpload(html, url);
}

function afterUploadEvents(html)
{
	// get album-id
	var albumId=0;
	var albumRegexp = /<albumId>([0-9]+)<\/albumId>/;
	var matches = resultRegexp.exec(html);
	if (matches!=null && matches[1]==matches[3]) {
		matches=albumRegexp.exec(html);
		if (matches!=null)
			albumId = matches[1];
	}
	url = 'events.php?m=pics_add&eid='+uploaderSectionValue+'&a='+albumId;
	afterUpload(html, url);
}

function afterUpload(html, url)
{
	var idRegexp = /<ids>([0-9, ]+)<\/ids>/;
	var matches = resultRegexp.exec(html);
	if (matches != null && matches[1] == matches[3]) {
		alert(matches[2]);
		// If any IDs were returned - go to edit page
		matches = idRegexp.exec(html);
		if (matches != null) {
			var idList = matches[1];
			window.location = url + '&editPics=fresh';//' + idList;
		}
	}
	else alert(html);
}

function delAlbum(id)
{
	MessageBox.confirm('?האם למחוק אלבום זה',delAlbumConfirm,id);
}

function delAlbumConfirm(id)
{
	var postInfo = 'delAlbum='+id+'&token='+token;
	doPostBack(postInfo);
}

function rotatePic(opt)
{
	if (!xhr) xhr = new XHR(20000);
	xhr.SetErrorFunc(rotatePicError);

	$('picRotateOpts').style.display = 'none';
	var textElement = $('picRotateText');
	textElement.innerHTML = 'מעבד תמונה...';
	textElement.style.display = 'block';
	xhr.Post(window.location,'rotate='+opt,rotatePicResult);
}

function rotatePicError(errorText)
{
	$('picRotateOpts').style.display = 'block';	
	$('picRotateText').style.display = 'none';
	alert(errorText);
}

function rotatePicResult(responseText)
{
	$('picRotateOpts').style.display = 'block';	
	$('picRotateText').style.display = 'none';
	try
	{
		// Parse result or error tags - Only 1 is allowed  
		var matches = resultRegexp.exec(responseText);
		if (matches == null || matches[1] != matches[3]) throw Error('תגובה לא תקנית');
		if (matches[1] == 'error') throw Error(matches[2]);
		var url = matches[2];
		$('picMain').src = url;
	}
	catch (ex)
	{
		alert(ex.message);
	}
}

function reportPic(albumId,picId)
{
	if (!canComplain)
	{
		MessageBox.alert('כבר התלוננתם');
		return;
	}
	var data = {"albumId":albumId,"picId":picId}
	MessageBox.confirm('האם להודיע להנהלת האתר על תמונה זאת?',reportPicConfirm,data);
}
function reportPicConfirm(data)
{
	if (xhr == null) xhr = new XHR(20000);
	var postInfo = 'type=albums&album_id='+data.albumId+'&pic_id='+data.picId;
	xhr.Post('complaint.php',postInfo,reportPicResult);
	$('complaintSpan').innerHTML = 'התלונה נשלחת...';	
}
function reportPicError(errorText)
{
	$('complaintSpan').innerHTML = "תוכן זה פוגע בי";
	MessageBox.alert(errorText);
}
function reportPicResult(responseText)
{
	if (responseText != 'ok')
	{
		reportPicError(responseText);
		return;
	}

	$('complaintSpan').innerHTML = 'התלונה נשלחה בהצלחה';
	canComplain = false;
}

function sendTag(id,tag)
{
	var dimensions = imagePointer.getDimensions();
	imagePointer.hideAll();
	if (tag == null || tag.length == 0 || tag == TagSearchBox.DEFAULT_INPUT_VALUE) return;
	// Will be passed to XHR result
	var data = {type:'ins'}
	data.id = id;
	data.tag = tag
	data.dimensions = dimensions;
	
	postInfo = 'tag=1&d[0]='+dimensions.x+'&d[1]='+dimensions.y+'&d[2]='+dimensions.w+'&d[3]='+dimensions.h;
	if (id != null && id.charAt(0) == 'u') postInfo += '&member_id=' + id.substr(1);
	else postInfo += '&content=' + tag;

	if (!xhr) xhr = new XHR(20000);
	xhr.Post(window.location,postInfo,sendTagResult,data);
}

function removeTag(id)
{
	var data = {type:'del'}
	data.id = id;
	postInfo = 'delTag=1&id='+id;
	if (!xhr) xhr = new XHR(20000);
	imagePointer.hideAll();
	xhr.Post(window.location,postInfo,sendTagResult,data);
}
/** Called both after insert, and after delete */
function sendTagResult(responseText,data)
{
	try
	{
		// Parse result or error tags - Only 1 is allowed  
		var matches = resultRegexp.exec(responseText);
		if (matches != null && matches[1] == matches[3])
		{
			if (matches[1] == 'error') throw Error(matches[2]);
			// Other option is 'result'
			$('tagReport').innerHTML = matches[2];
			responseText = responseText.substr(matches[0].length);
		}
		$('inThisPic').innerHTML = responseText;
		initPicTags();
	}
	catch (ex)
	{
		alert(ex.message);
	}
}
/** Searches for tags to display when mouse overs over image */
function picMainMouseMove(evt)
{
	var pos = getEventPos(evt);
	pos.x -= imagePointer.limits.l;
	pos.y -= imagePointer.limits.t;
	
	var tooltip = $('tooltip');
	// Collision detection
	for (var i=0;i<picTags.length;i++)
	{
		if (pos.x < picTags[i][0]) continue;
		if (pos.x > picTags[i][0] + picTags[i][2]) continue;
		if (pos.y < picTags[i][1]) continue;
		if (pos.y > picTags[i][1] + picTags[i][3]) continue;
		// We have a collision, gentlemen
		if (tooltip.style.display != 'block')
		{
			tooltip.innerHTML = picTags[i][4];
			tooltip.style.display = 'block';
			tooltip.style.left = (imagePointer.limits.l + picTags[i][0] + (picTags[i][2] - tooltip.offsetWidth) / 2) + 'px';
			tooltip.style.top = (imagePointer.limits.t + picTags[i][1] + picTags[i][3] - tooltip.offsetHeight) + 'px';
		}
		return;
	}
	// None found
	if (tooltip.style.display != 'none') tooltip.style.display = 'none';
}
function picMainMouseOut(evt)
{
	var target = getEventTo(evt);
	var tooltip = $('tooltip');
	if (target == tooltip) return;
	if (tooltip.style.display != 'none') tooltip.style.display = 'none';
}

function enableTagging()
{
	var picMain = $('picMain');
	nextPicFunc = picMain.onclick;
	picMain.onmousemove = null;
	picMain.onmouseout = null;
	$('tagReport').innerHTML = 'סמנו מי בתמונה:<br />מקמו את העכבר מעל הפנים של החבר שלכם,<br />לחצו וכתבו את הכינוי או מספר השין שלו, והשם שלו יופיע על התמונה';
	$('tagReportParent').style.display = 'block';
	imagePointer.enable();
	imagePointer.calcDimensions();
	imagePointer.searchWidget.onAfterSearch = sendTag;
	inTagMode = true;
}

function disableTagging()
{
	var picMain = $('picMain');
	imagePointer.disable();
	picMain.onclick = nextPicFunc;
	picMain.onmousemove = picMainMouseMove;
	picMain.onmouseout = picMainMouseOut;
	$('tagReportParent').style.display = 'none';
	imagePointer.calcDimensions();
	inTagMode = false;	
}

function initPicTags()
{
	var picTagSpans = tagListElement.getElementsByTagName('span');
	var posInfo = null;
	picTags = new Array();
	for (var i=0;i<picTagSpans.length;i++)
	{
		picTagSpans[i].onmouseover = showRectangle;
		picTagSpans[i].onmousout = stopPropagate;
		posInfo = picTagSpans[i].id.split(',');
		for (var j=0;j<4;j++) posInfo[j] = parseInt(posInfo[j]);
		// Get tag content, remove links and such
		posInfo[4] = picTagSpans[i].innerHTML;
		posInfo[4] = posInfo[4].replace(/\(.*\)/,'');
		posInfo[4] = posInfo[4].replace(/<\/?a[^>]*>/ig,'');
		picTags.push(posInfo);
	}
}

function initImagePointer()
{
	imagePointer = new ImagePointer("picMain",tagList);
	// Clean the global var
	tagList = null;
	inTagMode = false;
	var picMain = $('picMain');
	picMain.onmousemove = picMainMouseMove;
	picMain.onmouseout = picMainMouseOut;

	tagListElement = $('inThisPic');
	tagListElement.onmouseout = function() { if (!inTagMode) imagePointer.hideAll();}
	initPicTags();
}

function showRectangle(evt)
{
	stopPropagate(evt);
	if (inTagMode) return;
	var target = getEventTarget(evt);
	var id = null;
	if (target.id) id = target.id
	else if (target.parentNode.id) id = target.parentNode.id;
	else return;

	var posInfo = id.split(',');
	for (var i=0;i<4;i++) posInfo[i] = parseInt(posInfo[i]);

	imagePointer.setRectangle(posInfo[0],posInfo[1],posInfo[2],posInfo[3],false);
}
/** Called before unloading a single picture page */
function clearRequests()
{
	if (commentNavigator.request.InProgress()) commentNavigator.request.abort();
	if (xhr != null && xhr.InProgress()) xhr.abort();
}

function initSinglePhotoPage(numPerPage)
{
	CommentNavigator.prototype = new PageNavigator;
	commentNavigator = new CommentNavigator('comments', numPerPage, 2);

	commentNavigator.secondNavigator = $('topNavigator');
	// Set initial page
	PageNavigator.prototype.onRequestResult.call(commentNavigator,$('comments_container').innerHTML,0,'comments_count');
	commentNavigator.jumpElement = $('comments_numReport');

	if (picReady == 1) initImagePointer();
	else $('picMain').onload = initImagePointer;
}

function switchCommentSender()
{
	var title = $('senderSwitchTitle');
	var element = $("otherUserContainer");
	if (element.style.display == 'block')
	{
		// Reset shinId and password
		document.getElementsByName('shinId')[0].value = '';
		document.getElementsByName('pass')[0].value = '';
		title.innerHTML = 'שליחה בשם משתמש אחר';
		element.style.display = 'none';
	}
	else
	{
		element.style.display="block";
		title.innerHTML = 'שלח בשמך';
	}
}

/** Gallery comment navigator object */
function CommentNavigator(elementIdPrefix,numPerPage,pageSpan)
{
	var myself = this;
	PageNavigator.apply(this,arguments);
	
	this.request = new XHR(30000);
	this.serverScript = window.location;
	this.totalPages = 1;
	this.jumpToLastComment = false;
	
	this.onPageRequest = function(pageNum)
	{
		var postInfo = 'getComm=1&page='+(pageNum+1);
		this.request.Post(this.serverScript,postInfo,this.onRequestResult,pageNum);
	}

	this.onRequestResult = function(responseText,pageNum)
	{
		PageNavigator.prototype.onRequestResult.call(myself,responseText,pageNum,'comments_count');

		if (myself.jumpToLastComment)	// Has to be done AFTER populating the comments area
		{
			var comments = document.getElementsByName('picComment');
			comments[comments.length-1].scrollIntoView();
			myself.jumpToLastComment = false;
		}
		$('comments_numReport').innerHTML = (myself.numItems > 0) ? myself.numItems : '&nbsp;';
	}

	this.delItem = function(id)
	{
		MessageBox.confirm('?האם למחוק הערה זו',this.delItemConfirm,id);
	}

	this.delItemConfirm = function(id)
	{
		var postInfo = 'delComm='+id+'&page='+(myself.curPage+1);
		myself.request.Post(myself.serverScript,postInfo,myself.updateItemResult,'del');		
	}

	this.addItem = function(form)
	{
		var numericRegexp = /^[0-9]+$/
		try
		{
			if (this.request.InProgress()) throw Error('עסוק כרגע. נסו בעוד מספר רגעים.');
			var postInfo = 'addComm=1'; 

			var content = trim(form.elements['content'].value);
			if (content.length == 0) throw Error('יש למלא תוכן תגובה');
			if (content.length > 255) content = content.substr(0,255);
			postInfo += '&content='+XHR.Encode(content);

			var shinId = trim(form.elements['shinId'].value);
			var pass = trim(form.elements['pass'].value);
			if (shinId.length > 0 && pass.length > 0)
			{
				if (!numericRegexp.test(shinId)) throw Error('מספר שין לא תקני');
				postInfo += '&shinId='+shinId+'&pass='+pass;
			}
			this.request.Post(this.serverScript,postInfo,this.updateItemResult,'add');
		}
		catch (ex)
		{
			MessageBox.alert(ex.message);
		}
	}

	this.updateItemResult = function(responseText,act)
	{
		try
		{
			var matches = resultRegexp.exec(responseText);
			if (matches != null && matches[1] == matches[3])
			{
				if (matches[1] == 'error') throw Error(matches[2]);
				responseText = responseText.substr(matches[0].length);
			}
			var pageNum;
			if (act == 'add')
			{
				document.getElementsByName('content')[0].value = '';
				pageNum = 65532;
				myself.jumpToLastComment = true;
			}
			else if (act == 'del')
			{
				pageNum = myself.curPage;
			}

			myself.onRequestResult(responseText,pageNum);
		}
		catch (ex)
		{
			alert(ex.message);
		}
	}
}
