/*
CLASS GalleryItem
*/
var GalleryItem = Class.create();
GalleryItem.prototype =
{
	globalImgCache:{},

	initialize: function(obj, gallery)
	{
		//1. cache

//		this.ajaxUrl = '/gallery/';
		this.ajaxUrl = '/kiteboarding_az/gallery/';

		this.gallery = gallery;

		this.smallWidth = 70;
		this.smallHeight = 70;
		this.largeWidth = 390;
		this.largeHeight = 290;


		this.type = obj.type;
		this.image = obj.image;
		this.id = obj.id;
		this.title = obj.title;
		this.name = obj.name;
		this.email = obj.email;
		this.description = obj.description;
		this.date = obj.date;
		this.viewed = obj.viewed
		this.rating = obj.rating;
		this.commentsCount = obj.comments_count;
		this.alreadyRated = obj.already_rated;
		this.object = obj.object;
		this.alreadyInappropriate = obj.already_inappropriate;
		this.count = obj.count;
		this.num = obj.__num;
		/*
		try
		{
		if (!GalleryItem.prototype.globalImgCache[this.id])
		{
			GalleryItem.prototype.globalImgCache[this.id] = {};

			GalleryItem.prototype.globalImgCache[this.id]['small'] = new Image();
			GalleryItem.prototype.globalImgCache[this.id]['small'].src = this.getSmallImgSrc();

			GalleryItem.prototype.globalImgCache[this.id]['large'] = new Image();
			GalleryItem.prototype.globalImgCache[this.id]['large'].src = this.getLargeImgSrc();
		}

		}
		catch(e) {console.log(e);}
		*/
	},



	initDom: function()
	{

	},


	enableRating: function()
	{
		this.gallery.domRatingBar.setReadOnly(false);
		this.gallery.domRatingBar2.setReadOnly(false);
		Element.show(this.gallery.domLinkRateIt.parentNode);

		//safari workaround
		Element.hide(this.gallery.domRatingBar2.domSpanBar);
	},

	disableRating: function()
	{
		this.gallery.domRatingBar.setReadOnly(true);
		this.gallery.domRatingBar2.setReadOnly(true);
		Element.hide(this.gallery.domLinkRateIt.parentNode);
	},


	evalJSON: function(text)
	{
		try
		{
			eval('var xxx = '+text+';');
		}
		catch(e)
		{
			var xxx = null;
		}
		return xxx;
	},

	display: function(element, size)
	{
		this.domElement = element;
		this.size = size;


		if (this.type == 'gallery')
		{
			var tmp = $A(element.getElementsByTagName('img'));
			if (tmp.length > 0)
			{
				this.domImg = tmp[0];
			}

			if (!this.domImg)
			{
				this.domElement.innerHTML = '';
				this.domImg = document.createElement('img');
				this.domImg.alt = "";
				this.domImg.src = '/store/img/e.gif';
				this.domElement.appendChild(this.domImg);
			}


			//IE6 workaround: run in separate thead
			setTimeout(this.setImageSrc.bind(this), 50);
		}
		else //video
		{
			try
			{
				var embedCode = this.object.match(/<embed.+?embed>/);
				var domTmpDiv = document.createElement('div');
				domTmpDiv.innerHTML = embedCode[0];

				var tmp = Element.getElementsBySelector(domTmpDiv, 'embed');
				var embed = tmp[0];

				if (size == 'large')
				{
					embed.style.width = '';
					embed.style.height = '';
					embed.setAttribute('width', this.largeWidth);
					embed.setAttribute('height', this.largeHeight);

				}
				else
				{
					embed.style.width = '';
					embed.style.height = '';
					embed.setAttribute('width', this.smallWidth);
					embed.setAttribute('height', this.smallHeight);
					embed.style.display = 'none';
				}

				element.innerHTML = '';
				element.appendChild(embed);
			}
			catch(e)
			{
				element.innerHTML = '<span style="color: red">Bad object</span>';
			}
		}
	},



	setImageSrc: function()
	{
		/*
		this.domImg.src = GalleryItem.prototype.globalImgCache[this.id][this.size].src;
		return;
		*/


		if (this.size == 'small')
		{
			var src = this.getSmallImgSrc();
			var cacheSrc = this.getLargeImgSrc();
		}
		else
		{
			var src = this.getLargeImgSrc();
			var cacheSrc = this.getSmallImgSrc();
		}

		this.domImg.style.background = "url('"+src+"') no-repeat";
		this.domCacheSrc = new Image();
		this.domCacheSrc.src = cacheSrc;
	},

	clearImageSrc: function()
	{
		this.domImg.src = '/store/img/e.gif';
	},


	getImgSrc: function(w, h)
	{
		return '/store/image_resizer.php?w='+w+'&h='+h+'&i=/store/images/gallery/orig/'+this.image;
	},

	getSmallImgSrc: function()
	{
		return this.getImgSrc(this.smallWidth, this.smallHeight);
	},

	getLargeImgSrc: function()
	{
		return this.getImgSrc(this.largeWidth, this.largeHeight);
	},

	displayInfo: function()
	{
		this.gallery.domSpanViews.update(this.viewed);
		this.gallery.domSpanCommentsCount.update(this.commentsCount);
		this.gallery.domSpanDate.update(this.date);
		this.gallery.domSpanAuthor.update(this.name);
		this.gallery.domDivDescription.update(this.description);
		this.gallery.domDivTitle.update(this.title);

		this.gallery.domRatingBar.setRating(this.rating);
		this.gallery.domRatingBar.onRatingSet = this.onRatingClicked.bind(this);

		this.gallery.domRatingBar2.setRating(this.rating);
		this.gallery.domRatingBar2.onRatingSet = this.onRatingClicked.bind(this);

		this.gallery.domLinkEmail.onclick = this.showEmailPopup.bind(this);

		if (this.alreadyRated)
			this.disableRating();
		else
			this.enableRating();

		if (this.alreadyInappropriate)
			Element.hide(this.gallery.domLinkFlag.parentNode);
		else
			Element.show(this.gallery.domLinkFlag.parentNode);
	},

	onRatingClicked: function(rateBar, rating)
	{
		var params =
		{
			method: 'post',
			parameters: 'rpc=1&action=rate_item&rating='+rating+'&id='+this.id,
			onSuccess: this.onRatingUpdated.bind(this),
			onFailure: this.onAjaxFailed.bind(this)
		};
		new Ajax.Request(this.ajaxUrl, params);
	},

	onError: function(error)
	{
		alert(error);
	},

	onRatingUpdated: function(req)
	{
		var response = this.evalJSON(req.responseText);
		if (response.error)
		{
			this.onError(response.error);
			return;
		}

		this.rating = parseInt(response.data.rating);
		this.alreadyRated = 1;
		this.displayInfo();

		new PopUpAlert('Thank you', 'Thank you for rating this item', '30%', '220px', $('g_cont'));
	},


	incrementViews: function()
	{
		var params =
		{
			method: 'post',
			parameters: 'rpc=1&action=increment_views&id='+this.id,
			onSuccess: this.onViewsUpdated.bind(this),
			onFailure: this.onAjaxFailed.bind(this)
		};
		new Ajax.Request(this.ajaxUrl, params);
	},

	onViewsUpdated: function(req)
	{
		var response = this.evalJSON(req.responseText);
		if (response.error)
		{
			return;
		}



		this.viewed = parseInt(response.data.viewed);
		this.gallery.domSpanViews.update(this.viewed);

	},

	showEmailPopup: function()
	{
		var dialog = new PopUpEmail(this);
		dialog.onSubmit = this.onEmailPopupSubmit.bind(this);
		dialog.display();

	},

	onEmailPopupSubmit: function(data)
	{
		var params =
		{
			method: 'post',
			parameters: 'rpc=1&action=email&id='+this.id+'&'+$H(data).toQueryString(),
			onSuccess: this.onEmailSent.bind(this),
			onFailure: this.onAjaxFailed.bind(this)
		};
		new Ajax.Request(this.ajaxUrl, params);
	},

	onEmailSent: function(req)
	{
		new PopUpAlert('Thank you', 'Your email was sent to '+this.name, '30%', '220px', $('g_cont'));
	},

	onAjaxFailed:function()
	{
		alert('Ajax failed');
	},


	addComment: function()
	{
		var dialog = new PopAddComment(this.id);
		dialog.onSuccess = this.onCommentAdded.bind(this);
		dialog.display();
	},

	onCommentAdded: function(data)
	{
		this.displayComments();
	},

	displayComments: function(data)
	{
		var params =
		{
			method: 'post',
			parameters: 'rpc=1&action=get_comments&id='+this.id,
			onSuccess: this.onCommentsLoaded.bind(this),
			onFailure: this.onAjaxFailed.bind(this)
		};
		new Ajax.Request(this.ajaxUrl, params);
	},

	onCommentsLoaded: function(req)
	{
		var response = this.evalJSON(req.responseText);
		if (response.error)
		{
			return;
		}
		var data = response.data;


		this.gallery.domUlComments.innerHTML = '';

		try
		{
			for (var i = 0; i < data.comments.length; i++)
			{
				var domLiComment = document.createElement('li');

				var domDivHeader = document.createElement('div');
				Element.addClassName(domDivHeader, 'g_header');
				domLiComment.appendChild(domDivHeader);

				var domSpanAuthor = document.createElement('span');
				Element.addClassName(domSpanAuthor, 'g_author');
				domSpanAuthor.appendChild(document.createTextNode(data.comments[i]['name']));
				domDivHeader.appendChild(domSpanAuthor);

				var domSpanDate = document.createElement('span');
				Element.addClassName(domSpanDate, 'g_date');
				domSpanDate.appendChild(document.createTextNode(data.comments[i]['date']));
				domDivHeader.appendChild(domSpanDate);

				var domDivBody = document.createElement('div');
				Element.addClassName(domDivBody, 'g_body');
				domDivBody.appendChild(document.createTextNode(data.comments[i]['comment']));
				domLiComment.appendChild(domDivBody);

				var domDivActions = document.createElement('div');
				Element.addClassName(domDivActions, 'g_actions');
				domLiComment.appendChild(domDivActions);

				var domLinkSpam = document.createElement('a');
				domLinkSpam.href = 'javascript:void(0)';
				domLinkSpam.innerHTML = 'spam';
				domLinkSpam.setAttribute('comment_id', data.comments[i]['id']);
				if (data.comments[i]['already_spam'] == '1')
					domLinkSpam.style.visibility = 'hidden';


				domDivActions.appendChild(domLinkSpam);
				Event.observe(domLinkSpam, 'click', this.markAsSpam.bind(this, data.comments[i]['id']));


				this.gallery.domUlComments.appendChild(domLiComment);

			}
		}
		catch(e)
		{

		}


		this.commentsCount = data.comments.length;
		this.gallery.domSpanCommentsCount.update(this.commentsCount);
	},

	markAsSpam: function(id)
	{
		var params =
		{
			method: 'post',
			parameters: 'rpc=1&action=mark_spam&id='+id,
			onSuccess: this.spamMarked.bind(this, id),
			onFailure: this.onAjaxFailed.bind(this)
		};
		new Ajax.Request(this.ajaxUrl, params);
	},

	spamMarked: function(id, req)
	{
		var tmp = Element.getElementsBySelector(this.gallery.domUlComments, 'a[comment_id='+id+']');
		var domLink = tmp[0];

		var pos = Position.positionedOffset(domLink);
		var parent = Position.offsetParent(domLink);

		domLink.style.visibility = 'hidden';

		new PopUpAlert('Thank you', 'Comment was marked as spam', '30%', pos[1]-80+'px', parent);

	},

	flagAsInappropriate: function()
	{
		var params =
		{
			method: 'post',
			parameters: 'rpc=1&action=flag_inappropriate&id='+this.id,
			onSuccess: this.inappropriateFlagged.bind(this),
			onFailure: this.onAjaxFailed.bind(this)
		};
		new Ajax.Request(this.ajaxUrl, params);
	},

	inappropriateFlagged: function(req)
	{
		this.alreadyInappropriate = 1;
		Element.hide(this.gallery.domLinkFlag.parentNode);
		new PopUpAlert('Thank you', 'Item was flagged as inappropriate', '30%', '300px', $('g_cont'));
	},

	enlarge: function()
	{
		new PopUpImage(this.title, '/store/images/gallery/orig/'+this.image, '10px', '10px', 610, 440, $('g_cont'));
	}


};












/*
CLASS Gallery
*/
var Gallery = Class.create();
Gallery.prototype =
{
	initialize: function(containerId, itemType, sort, id)
	{
//		this.ajaxUrl = '/gallery/';
		this.ajaxUrl = '/kiteboarding_az/gallery/';
		this.itemType = itemType;


		this.domDivContainer = $(containerId);
		if (this.itemType == 'video')
		{
			Element.addClassName(this.domDivContainer, 'g_video');
		}

		this.initDom();
		this.getItems(sort, id)
	},

	initDom: function()
	{
		var tmp = Element.getElementsBySelector(this.domDivContainer, 'td.g_item');
		this.domTdPrev = tmp[0];
		this.domTdCurr = tmp[1];
		this.domTdNext = tmp[2];

		tmp = Element.getElementsBySelector(this.domDivContainer, 'td.g_item .g_item_container');
		this.domItemContainerPrev = tmp[0];
		this.domItemContainerCurr = tmp[1];
		this.domItemContainerNext = tmp[2];

		//get prev and next links
		tmp = Element.getElementsBySelector(this.domDivContainer, 'td.g_item .g_title a');
		this.domLinkPrev = tmp[0];
		this.domLinkNext = tmp[1];

		tmp = Element.getElementsBySelector(this.domDivContainer, 'td.g_item .g_title');
		this.domDivTitle = tmp[1];


		tmp = Element.getElementsBySelector(this.domDivContainer, '.g_sort_types a');
		this.domLinkSearch = tmp[0];
		this.domLinkMostRecent = tmp[1];
		this.domLinkMostViewed = tmp[2];
		this.domLinkTopRated = tmp[3];
		this.domLinkMostDiscussed = tmp[4];


		tmp = Element.getElementsBySelector(this.domDivContainer, '.g_info');
		this.domDivInfo = tmp[0];

		tmp = Element.getElementsBySelector(this.domDivContainer, '.g_info .g_value');
		this.domSpanViews = tmp[0];
		this.domSpanCommentsCount = tmp[1];
		this.domSpanDate = tmp[2];
		this.domSpanAuthor = tmp[3];
		this.domRatingBar = new StarRater(5);
		this.domRatingBar.display(this.domDivInfo);


		tmp = Element.getElementsBySelector(this.domDivContainer, '.g_description');
		this.domDivDescription = tmp[0];


		tmp = Element.getElementsBySelector(this.domDivContainer, '.g_actions a');
		this.domLinkAddComment = tmp[0];
		this.domLinkRateIt = tmp[1];
		this.domLinkEmail = tmp[2];
		this.domLinkEnlarge = tmp[3];
		this.domLinkFlag = tmp[4];
		this.domLinkSubmit = tmp[5];


		if (this.itemType == 'video')
		{
			Element.hide(this.domLinkEnlarge.parentNode);
		}


		/* popup rating */
		this.domRatingBar2 = new StarRater(5);
		this.domRatingBar2.display(this.domLinkRateIt);
		Element.hide(this.domRatingBar2.domSpanBar);
		Event.observe(this.domLinkRateIt, 'mouseover', this.rateItMouseOver.bind(this));
		Event.observe(this.domLinkRateIt, 'mouseout', this.rateItMouseOut.bind(this));



		tmp = Element.getElementsBySelector(this.domDivContainer, 'ul.g_comments');
		this.domUlComments = tmp[0];



		//add events
		Event.observe(this.domLinkPrev, 'click', this.onPrevious.bind(this));
		Event.observe(this.domLinkNext, 'click', this.onNext.bind(this));

		if (this.itemType == 'gallery')
		{
			Event.observe(this.domItemContainerPrev, 'click', this.onPrevious.bind(this));
			Event.observe(this.domItemContainerNext, 'click', this.onNext.bind(this));
			Event.observe(this.domItemContainerCurr, 'click', this.onEnlarge.bind(this));
		}


		Event.observe(this.domLinkSearch, 'click', this.onSearch.bind(this));
		Event.observe(this.domLinkMostRecent, 'click', this.onSort.bind(this, 'most_recent'));
		Event.observe(this.domLinkMostViewed, 'click', this.onSort.bind(this, 'most_viewed'));
		Event.observe(this.domLinkTopRated, 'click', this.onSort.bind(this, 'top_rated'));
		Event.observe(this.domLinkMostDiscussed, 'click', this.onSort.bind(this, 'most_discussed'));

		Event.observe(this.domLinkSubmit, 'click', this.onSubitItem.bind(this));
		Event.observe(this.domLinkAddComment, 'click', this.onAddComment.bind(this));
		Event.observe(this.domLinkFlag, 'click', this.onFlagInapporiate.bind(this));

		Event.observe(this.domLinkEnlarge, 'click', this.onEnlarge.bind(this));


		//fix images
		//new PeriodicalExecuter(this.fixAllImages.bind(this), 2);


	},


	onAjaxFailed: function(req)
	{
		alert('Ajax request failed');
	},
	
	onError: function(error)
	{
		alert(error);
	},

	evalJSON: function(text) //not implement on ksmaui's version of prototype.js
	{
		try
		{
			eval('var xxx = '+text+';');
		}
		catch(e)
		{
			var xxx = null;
		}
		return xxx;
	},

	getItems: function(sort, id)
	{

		this.sort = sort;
		this.id = id?id:0;

		var params =
		{
			method: 'post',
			parameters: 'rpc=1&action=get_items&itemType='+this.itemType+'&sort='+this.sort+'&id='+this.id+'&'+Form.serializeElements([$('g_search_input')]),
			onSuccess: this.onItemsLoaded.bind(this),
			onFailure: this.onAjaxFailed.bind(this)
		};
		new Ajax.Request(this.ajaxUrl, params);
	},

	onItemsLoaded: function(req)
	{
		var response = this.evalJSON(req.responseText);
		
		if (response.error)
		{
			this.onError(response.error);
			return;
		}

		var items = response.data;
		this.items = {};
		for (var i in items)
		{
			this.items[i] = new GalleryItem(items[i], this);
		}

		this.id = this.items['current'].id;

		this.updateItems();
	},

	updateItems: function()
	{
		//prev
		if (this.items['previous'])
		{
			this.domItemContainerPrev.show();
			this.domLinkPrev.show();

			this.items['previous'].display(this.domItemContainerPrev, 'small');
		}
		else
		{
			this.domLinkPrev.hide();
			this.domItemContainerPrev.hide();
		}

		//next
		try
		{
			if (this.items['next'])
			{
				this.domLinkNext.show();
				this.domItemContainerNext.show();
				this.items['next'].display(this.domItemContainerNext, 'small');
			}
			else
			{
				this.domLinkNext.hide();
				this.domItemContainerNext.hide();
			}
		}
		catch(e)
		{
			var er = '';
			for(var x in e)
			{
				er += (x+': '+e[x]+"\n");
			}
			alert(er);
		}



		//current
		this.items['current'].display(this.domItemContainerCurr, 'large');
		this.items['current'].displayInfo();
		this.items['current'].incrementViews();
		this.items['current'].displayComments();

		//pager
		$("pager").innerHTML = '<a href="javascript:gallery.onPrevious()">&lt; Prev</a> | ' + this.items['current'].num + ' of ' + this.items['current'].count + ' | <a href="javascript:gallery.onNext()">Next &gt;</a>';

	},

	onPrevious: function(event)
	{
		this.getItems(this.sort, this.items['previous'].id);
	},

	onNext: function(event)
	{
		this.getItems(this.sort, this.items['next'].id);
	},

	onSort: function(sort, event)
	{
		this.getItems(sort);
	},

	rateItMouseOver: function()
	{
		if (this.rateItTimer)
		{
			clearTimeout(this.rateItTimer);
			this.rateItTimer = null;
		}

		Element.show(this.domRatingBar2.domSpanBar);
		//safari workaround. without it id doesn't updates stars on hover
		this.domDivDescription.innerHTML += '';
	},

	rateItMouseOut: function()
	{
		this.rateItTimer = setTimeout(this.rateItMouseOutOnTimer.bind(this), 600);
	},

	rateItMouseOutOnTimer: function()
	{
		Element.hide(this.domRatingBar2.domSpanBar);
		this.rateItTimer = null;
	},


	onSubitItem: function()
	{
		var dialog = new PopUpSubmit(this.itemType);
		dialog.display();
	},

	onAddComment: function()
	{
		this.items['current'].addComment();

	},

	onFlagInapporiate: function()
	{
		this.items['current'].flagAsInappropriate();
	},

	onEnlarge: function()
	{
		this.items['current'].enlarge();
	},


	onSearch: function()
	{
		var query = $F('g_search_input');
		if (query == '')
		{
			alert('Empty search string');
			return;
		}

		var params =
		{
			method: 'post',
			parameters: 'rpc=1&action=get_items&itemType='+this.itemType+'&id=0&sort=search&'+Form.serializeElements([$('g_search_input')]),
			onSuccess: this.onSearchComplete.bind(this),
			onFailure: this.onAjaxFailed.bind(this)
		};
		new Ajax.Request(this.ajaxUrl, params);
	},


	onSearchComplete:function(req)
	{
		var response = this.evalJSON(req.responseText);
		if (response.error)
		{
			new PopUpAlert('Nothing found', 'There is no items matching your search', '30%', '300px', $('g_cont'));
			return;
		}

		this.sort = 'search';
		this.onItemsLoaded(req);
	},


	hideAllVideos: function()
	{
		var videos = Element.getElementsBySelector(this.domDivContainer, 'td.g_item embed');
		videos.each(function(vid){
			vid.style.visibility = 'hidden';
		});
	},

	unHideAllVideos: function()
	{
		var videos = Element.getElementsBySelector(this.domDivContainer, 'td.g_item embed');
		videos.each(function(vid){
			vid.style.visibility = 'visible';
		});
	},

	fixAllImages: function()
	{
		var images = Element.getElementsBySelector(this.domDivContainer, 'td.g_item img');
		images.each(function(img){
			img.src = img.src;
		});
	}





};






/*
CLASS StarRater
*/
var StarRater = Class.create();
StarRater.prototype = {
	initialize: function(num, rating)
	{
		var preload = new Image();
		preload.src = '/store/img/rate_star2.gif';
		preload.src = '/store/img/rate_star_empty2.gif';
		preload.src = '/store/img/rate_star_hover2.gif';


		this.num = num;
		this.rating = rating?rating:0;
		this.readonly = false;


		this.initDom();
		this.setRating(this.rating);
	},

	initDom: function()
	{
		this.domSpanBar = document.createElement('span');
		Element.addClassName(this.domSpanBar, 'g_rating_bar')
		Event.observe(this.domSpanBar, 'mouseover', this.onMouseOver.bindAsEventListener(this));
		Event.observe(this.domSpanBar, 'mouseout', this.onMouseOut.bindAsEventListener(this));
		Event.observe(this.domSpanBar, 'click', this.onClick.bindAsEventListener(this));
		Event.observe(this.domSpanBar, 'focus', this.onFoucus.bindAsEventListener(this));

		for (var i = 0; i < this.num; i++)
		{
			var star = document.createElement('a');
			star.href = "javascript:void(0)";



			star.setAttribute('rating', i+1);
			star.className = 'g_star';
			this.domSpanBar.appendChild(star);
		}
	},

	display: function(element)
	{
		this.domElement = element;
		this.domElement.appendChild(this.domSpanBar);
	},

	setReadOnly: function(val)
	{
		this.readOnly = val;
	},

	setRating: function(val)
	{
		this.rating = val;
		var stars = Element.getElementsBySelector(this.domSpanBar, 'a');
		for (var i = 0; i < this.num; i++)
		{
			if (i < val)
				stars[i].className = 'g_star';
			else
				stars[i].className = 'g_star_empty';
		}
	},

	onMouseOver: function(event)
	{
		this.setRating(this.rating);
		if (this.readOnly)
			return;

		var j = parseInt(Event.element(event).getAttribute('rating'));
		var stars = Element.getElementsBySelector(this.domSpanBar, 'a');
		for (var i = 0; i < j; i++)
		{
			stars[i].className = 'g_star_hover';
		}
	},

	onMouseOut: function(event)
	{
		this.setRating(this.rating);
	},

	onFoucus: function(event)
	{
		Event.element(event).blur();
	},

	onClick: function(event)
	{
		if (this.readOnly)
		{
			new PopUpAlert('Already Rated', 'You have already rated this item.', '30%', '220px', $('g_cont'));
			return;
		}

		var j = parseInt(Event.element(event).getAttribute('rating'));
		this.onRatingSet(this, j);
	},

	onRatingSet: function(ratingBar, rating)
	{

		this.domDivContainer
	}

};









/*
CLASS PopUpAlert
*/
var PopUpAlert = Class.create();
PopUpAlert.prototype = {
	initialize: function(title, text, x, y, element)
	{
		this.initDom(title, text, x, y);
		this.show(element);
	},

	initDom: function(title, text, x, y)
	{
		this.domDivContainer = document.createElement('div');
		Element.addClassName(this.domDivContainer, 'g_popup_container');

		this.domDivInner = document.createElement('div');
		Element.addClassName(this.domDivInner, 'g_popup_inner');
		this.domDivContainer.appendChild(this.domDivInner);

		this.domDivHeader = document.createElement('div');
		this.domDivHeader.innerHTML = title;
		Element.addClassName(this.domDivHeader, 'g_popup_header');
		this.domDivInner.appendChild(this.domDivHeader);

		this.domDivBody = document.createElement('div');
		Element.addClassName(this.domDivBody, 'g_popup_body');
		this.domDivBody.innerHTML = text;
		this.domDivInner.appendChild(this.domDivBody);

		this.domDivFooter = document.createElement('div');
		Element.addClassName(this.domDivFooter, 'g_popup_footer');
		this.domDivInner.appendChild(this.domDivFooter);

		this.domLinkClose = document.createElement('a');
		this.domLinkClose.href = 'javascript:void(0)';
		this.domLinkClose.appendChild(document.createTextNode('close'));
		Event.observe(this.domLinkClose, 'click', this.close.bind(this));
		this.domDivFooter.appendChild(this.domLinkClose);

		this.domImgDummy = document.createElement('img');
		this.domImgDummy.src = '/store/img/e.gif';
		this.domImgDummy.style.width = '300px';
		this.domImgDummy.style.height = '1px';
		this.domImgDummy.style.border = 'none';
		this.domImgDummy.style.display = 'block';
		this.domDivInner.appendChild(this.domImgDummy);

		this.domDivContainer.style.top = y;
		this.domDivContainer.style.left = x;
	},


	show: function(element)
	{
		element.appendChild(this.domDivContainer);
	},

	close: function()
	{
		Element.remove(this.domDivContainer);
		return false;
	}
};








/*
CLASS PopUpEmail
*/
var PopUpEmail = Class.create();
PopUpEmail.prototype = {
	initialize: function(item)
	{
		this.domDivContainer = $('g_popup_email');
		var tmp = Element.getElementsBySelector(this.domDivContainer, '.g_popup_inner .g_popup_footer a');
		this.domLinkSubmit = tmp[0];
		this.domLinkClose = tmp[1];


		tmp = Element.getElementsBySelector(this.domDivContainer, '.g_popup_inner .g_popup_header');
		this.domDivHeader = tmp[0];
		this.domDivHeader.innerHTML = 'E-mail to '+item.name;

		tmp = Element.getElementsBySelector(this.domDivContainer, 'input', 'textarea');
		this.domInputName = tmp[0];
		this.domInputEmail = tmp[1];
		this.domInputNote = tmp[2];

		tmp = Element.getElementsBySelector(this.domDivContainer, '.g_errors');
		this.domDivErrors = tmp[0];

		this.initHandlers();
	},

	initHandlers: function()
	{
		if (!PopUpEmail.prototype.handlersInited)
		{
			PopUpEmail.prototype.handlersInited = true;
			Event.observe(this.domLinkClose, 'click', this.close.bind(this));
			Event.observe(this.domLinkSubmit, 'click', this.onSubmitInternal.bind(this));
		}
	},

	close: function()
	{
		this.domDivContainer.hide();
		gallery.unHideAllVideos();
	},

	display: function()
	{
		gallery.hideAllVideos();

		this.domDivContainer.style.left = '20px';
		this.domDivContainer.style.top = '250px';
		this.domDivContainer.show();

		this.domDivErrors.innerHTML = '';
		this.domInputName.value = '';
		this.domInputEmail.value = '';
		this.domInputNote.value = '';

	},

	onSubmitInternal: function()
	{
		var data =
		{
			name: $F(this.domInputName),
			email: $F(this.domInputEmail),
			note: $F(this.domInputNote)
		};

		var res = this.validate(data);
		if (res)
		{

			this.domDivErrors.innerHTML = res;
			return;
		}

		this.close();
		this.onSubmit(data);



	},

	validate: function(data)
	{
		var errorsHTML = '';
		if (data.name.length == 0)
			errorsHTML += 'Please fill in name<br />';

		if (!data.email.match(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_.-]+\.[a-z]{2,4}$/))
			errorsHTML += 'E-mail seems to be invalid<br />';

		if (data.note.length == 0)
			errorsHTML += 'Please fill in note<br />';

		return errorsHTML;
	},

	onSubmit: function()
	{

	}
};







/*
CLASS PopSubmit
*/
var PopUpSubmit = Class.create();
PopUpSubmit.prototype = {
	initialize: function(type)
	{
//		this.ajaxUrl = '/gallery/';
		this.ajaxUrl = '/kiteboarding_az/gallery/';

		this.domDivContainer = $('g_popup_submit');
		var tmp = Element.getElementsBySelector(this.domDivContainer, '.g_popup_inner .g_popup_footer a');
		this.domLinkSubmit = tmp[0];
		this.domLinkClose = tmp[1];


		tmp = Element.getElementsBySelector(this.domDivContainer, '.g_popup_inner .g_popup_header');
		this.domDivHeader = tmp[0];
		this.domDivHeader.innerHTML = 'Submit ' + ((type=='gallery')?'Image':'Video');


		tmp = Element.getElementsBySelector(this.domDivContainer, 'input', 'textarea');
		this.domInputTitle = tmp[0];
		this.domInputName = tmp[1];
		this.domInputEmail = tmp[2];
		this.domInputDesc = tmp[3];
		this.domInputObj = tmp[4];




		tmp = Element.getElementsBySelector(this.domDivContainer, '.g_errors');
		this.domDivErrors = tmp[0];



		this.type = type;
		if (this.type == 'video')
		{
			$('g_submit_item_label').update('Flash Object: ');
			$('g_upload_thumb').hide();
			$('g_upload_link').hide();
		}
		else
		{
			$('g_submit_item_label').update('Image: ');
			$('g_upload_thumb').show();
			$('g_upload_link').show();
			this.domInputObj.hide();

		}


		this.initHandlers();
		this.image = null;

	},

	initHandlers: function()
	{
		if (!PopUpSubmit.prototype.handlersInited)
		{
			PopUpSubmit.prototype.handlersInited = true;
			Event.observe(this.domLinkClose, 'click', this.close.bind(this));
			Event.observe(this.domLinkSubmit, 'click', this.onSubmitInternal.bind(this));
			Event.observe($('g_upload_link'), 'click', this.showUploader.bind(this));
		}
	},

	display: function()
	{
		gallery.hideAllVideos();

		this.domDivErrors.innerHTML = '';
		Element.getElementsBySelector(this.domDivContainer, 'input', 'textarea').each(function(e){
			e.value = '';
		});

		this.domDivContainer.style.left = '50px';
		this.domDivContainer.style.top = '250px';
		this.domDivContainer.show();



	},

	close: function()
	{
		this.domDivContainer.hide();
		if (this.uploader)
			this.uploader.hide();

		gallery.unHideAllVideos();
	},

	onSubmitInternal: function()
	{
		var data =
		{
			type: this.type,
			title: $F(this.domInputTitle),
			name: $F(this.domInputName),
			email: $F(this.domInputEmail),
			description: $F(this.domInputDesc),
			object: $F(this.domInputObj),
			image: this.image
		};

		var params =
		{
			method: 'post',
			parameters: 'rpc=1&action=submit&'+$H(data).toQueryString(),
			onSuccess: this.submissionResult.bind(this),
			onFailure: this.onAjaxFailed.bind(this)
		};
		new Ajax.Request(this.ajaxUrl, params);
	},

	submissionResult: function(req)
	{
		var response = this.evalJSON(req.responseText);
		if (response.error)
		{
			this.domDivErrors.innerHTML = response.error;
			return;
		}



		this.close();
		new PopUpAlert('Thank you', 'Thank you for submission', '30%', '220px', $('g_cont'));

	},

	onAjaxFailed: function(req)
	{
		alert('Ajax request failed');
	},



	evalJSON: function(text) //not implement on ksmaui's version of prototype.js
	{
		try
		{
			eval('var xxx = '+text+';');
		}
		catch(e)
		{
			var xxx = null;
		}
		return xxx;
	},

	onFileUploaded: function(responseText)
	{
		var response = this.evalJSON(responseText);
		if (response.error)
		{
			alert(response.error);
			return;
		}
		else
		{
			this.image = response.data.filename;
			setTimeout(this.showPreview.bind(this), 100);
		}
	},

	showUploader: function()
	{
		this.uploader = new PFileUpload(this.ajaxUrl, {rpc:1, action:'upload_image'});
		this.uploader.onUpload = this.onFileUploaded.bind(this);
		this.uploader.show(this.domDivContainer);
	},

	showPreview: function()
	{
		$('g_upload_thumb').src = '/store/image_resizer.php?w='+70+'&h='+70+'&i=/store/images/gallery/orig/'+this.image;
	}



};



/*
CLASS PopAddComment
*/
var PopAddComment = Class.create();
PopAddComment.prototype = {
	initialize: function(itemId)
	{
//		this.ajaxUrl = '/gallery/';
		this.ajaxUrl = '/kiteboarding_az/gallery/';

		this.domDivContainer = $('g_popup_comment');
		var tmp = Element.getElementsBySelector(this.domDivContainer, '.g_popup_inner .g_popup_footer a');
		this.domLinkSubmit = tmp[0];
		this.domLinkClose = tmp[1];


		tmp = Element.getElementsBySelector(this.domDivContainer, 'form');
		this.domForm = tmp[0];

		tmp = Element.getElementsBySelector(this.domDivContainer, '.g_errors');
		this.domDivErrors = tmp[0];

		this.itemId = itemId;

		this.initHandlers();
	},


	initHandlers: function()
	{
		if (!PopAddComment.prototype.handlersInited)
		{
			PopAddComment.prototype.handlersInited = true;
			Event.observe(this.domLinkClose, 'click', this.close.bind(this));
			Event.observe(this.domLinkSubmit, 'click', this.onSubmit.bind(this));
		}
	},

	close: function()
	{
		this.domDivContainer.hide();
		gallery.unHideAllVideos();
	},

	display: function()
	{
		gallery.hideAllVideos();
		this.domDivContainer.style.left = '20px';
		this.domDivContainer.style.top = '250px';
		this.domDivContainer.show();

		this.domDivErrors.innerHTML = '';
		Form.reset(this.domForm);
	},

	onSubmit: function()
	{


		var params =
		{
			method: 'post',
			parameters: 'rpc=1&action=add_comment&id='+this.itemId+'&'+Form.serialize(this.domForm),
			onSuccess: this.onRequestComplete.bind(this),
			onFailure: this.onAjaxFailed.bind(this)
		};
		new Ajax.Request(this.ajaxUrl, params);

	},

	onRequestComplete: function(req)
	{
		var response = this.evalJSON(req.responseText);
		if (response.error)
		{
			this.domDivErrors.innerHTML = response.error;
			return;
		}



		this.close();
		new PopUpAlert('Thank you', 'Your comment was added', '30%', '220px', $('g_cont'));
		this.onSuccess();
	},

	onSuccess: function()
	{
		alert('done');
	},

	onAjaxFailed: function(req)
	{
		alert('Ajax request failed');
	},



	evalJSON: function(text) //not implement on ksmaui's version of prototype.js
	{
		try
		{
			eval('var xxx = '+text+';');
		}
		catch(e)
		{
			var xxx = null;
		}
		return xxx;
	}

};

var PopUpImage = Class.create();
PopUpImage.prototype = {
	initialize: function(title, src, x, y, w, h, element)
	{
		this.w = w;
		this.h = h;
		this.src = src;

		this.initDom(title, x, y);
		this.show(element);
	},

	initDom: function(title, x, y)
	{
		this.domDivContainer = document.createElement('div');
		Element.addClassName(this.domDivContainer, 'g_popup_container');

		this.domDivInner = document.createElement('div');
		Element.addClassName(this.domDivInner, 'g_popup_inner');
		this.domDivContainer.appendChild(this.domDivInner);

		this.domDivHeader = document.createElement('div');
		this.domDivHeader.innerHTML = title;
		Element.addClassName(this.domDivHeader, 'g_popup_header');
		this.domDivInner.appendChild(this.domDivHeader);

		this.domDivBody = document.createElement('div');
		Element.addClassName(this.domDivBody, 'g_popup_body');
		this.domDivBody.style.overflow = 'auto';
		this.domDivBody.style.width = this.w+'px';
		this.domDivBody.style.height = this.h+'px';
		this.domDivInner.appendChild(this.domDivBody);

		this.domDivBody.innerHTML = '<table cellspacing="0" cellpadding="0" border="0" class="g_img_wrapper"><tbody><tr><td></td></tr></tbody></table>';
		var tmp = Element.getElementsBySelector(this.domDivBody, 'td');
		this.domTd = tmp[0];

		this.domImg = document.createElement('img');
		this.domImg.style.border = 'solid 1px black';
		this.domTd.appendChild(this.domImg);
		setTimeout(this.setImgSrc.bind(this), 100);


		this.domDivFooter = document.createElement('div');
		Element.addClassName(this.domDivFooter, 'g_popup_footer');
		this.domDivInner.appendChild(this.domDivFooter);

		this.domLinkClose = document.createElement('a');
		this.domLinkClose.href = 'javascript:void(0)';
		this.domLinkClose.appendChild(document.createTextNode('close'));
		Event.observe(this.domLinkClose, 'click', this.close.bind(this));
		this.domDivFooter.appendChild(this.domLinkClose);

		this.domImgDummy = document.createElement('img');
		this.domImgDummy.src = '/store/img/e.gif';
		this.domImgDummy.style.width = '300px';
		this.domImgDummy.style.height = '1px';
		this.domImgDummy.style.border = 'none';
		this.domImgDummy.style.display = 'block';
		this.domDivInner.appendChild(this.domImgDummy);

		this.domDivContainer.style.top = y;
		this.domDivContainer.style.left = x;


		//this.sizeFixer = new PeriodicalExecuter(this.fixSize.bind(this), 0.5);

	},


	show: function(element)
	{
		element.appendChild(this.domDivContainer);
	},

	close: function()
	{
		//this.sizeFixer.stop();
		Element.remove(this.domDivContainer);
		return false;
	},
	/*
	fixSize: function()
	{
		var size = Element.getDimensions(this.domDivBody);

		if (size.width > this.w)
			this.domDivBody.style.width = this.w+'px';

		if (size.height > this.h)
			this.domDivBody.style.height = this.h+'px';
	},
	*/
	setImgSrc: function()
	{
		this.domImg.src = this.src;
	}

};



/*
CLASS PFileUpload
*/
var PFileUpload = Class.create();
PFileUpload.prototype =
{
	lastObjectId: 1,

	initialize: function(uploadUrl, params)
	{
		this.objectId = PFileUpload.prototype.lastObjectId;
		PFileUpload.prototype.lastObjectId++;

		this.instructions = 'Please choose file and click "upload"';

		this.uploadUrl = uploadUrl;
		this.params = params?params:null;
		this.createDomElements();


	},

	createDomElements: function(element)
	{
		this.domIframeName = 'uploader_iframe_'+this.objectId;
		this.domFormName = 'uploader_form_'+this.objectId;


		this.domDivUploader = document.createElement('div');
		Element.addClassName(this.domDivUploader, 'p_uploader');


		this.domDivContainer = document.createElement('div');
		Element.addClassName(this.domDivContainer, 'p_container');
		this.domDivUploader.appendChild(this.domDivContainer);

		this.domDivInstructions = document.createElement('div');
		Element.addClassName(this.domDivInstructions, 'p_instructions');
		this.domDivInstructions.appendChild(document.createTextNode(this.instructions));
		this.domDivContainer.appendChild(this.domDivInstructions);

		this.domIframe = document.createElement('iframe');
		this.domIframe.style.width = '0';
		this.domIframe.height.width = '0';
		this.domIframe.style.border = 'none';
		this.domIframe.setAttribute('id', this.domIframeName);
		this.domIframe.setAttribute('name', this.domIframeName);
		this.domIframe.setAttribute('src', 'about:blank');
		document.body.appendChild(this.domIframe);
		if(self.frames[this.domIframeName].name != this.domIframeName)
		{
			//ie and safari fix
			self.frames[this.domIframeName].name = this.domIframeName;
		}
		Event.observe(this.domIframe, 'load', this.onFrameLoad.bindAsEventListener(this));

		this.domForm = document.createElement('form');
		this.domForm.setAttribute('name', this.domFormName);
		this.domForm.setAttribute('method', 'post');
		this.domForm.setAttribute('action', this.uploadUrl);
		this.domForm.setAttribute('target', this.domIframeName);
		this.domForm.setAttribute("enctype","multipart/form-data");
 		this.domForm.setAttribute("encoding","multipart/form-data");
 		this.domDivContainer.appendChild(this.domForm);







 		if (this.params)
 		{
			for (var key in this.params)
 			{
 				var val = this.params[key] + '';
 				var key = key + '';

 				var domTmpInput = document.createElement('input');
 				domTmpInput.setAttribute('type', 'hidden');
 				domTmpInput.setAttribute('name', key.escapeHTML());
 				domTmpInput.setAttribute('value', val.escapeHTML());
 				this.domForm.appendChild(domTmpInput);
 			}
 		}


 		this.domInputFile = document.createElement('input');
 		this.domInputFile.setAttribute('type', 'file');
 		this.domInputFile.setAttribute('name', 'upload');
 		this.domForm.appendChild(this.domInputFile);

 		this.domDivActions = document.createElement('div');
 		Element.addClassName(this.domDivActions, 'p_actions');
 		this.domDivContainer.appendChild(this.domDivActions);

 		this.domLinkSubmit = document.createElement('a');
 		this.domLinkSubmit.href = 'javascript:void(0)';
 		this.domLinkSubmit.innerHTML = 'upload';
 		Event.observe(this.domLinkSubmit, 'click', this.submitForm.bindAsEventListener(this));
 		this.domDivActions.appendChild(this.domLinkSubmit);

 		this.domDivActions.appendChild(document.createTextNode(' | '));

 		this.domLinkClose = document.createElement('a');
 		this.domLinkClose.href = 'javascript:void(0)';
 		this.domLinkClose.innerHTML = 'close';
 		Event.observe(this.domLinkClose, 'click', this.hide.bindAsEventListener(this));
 		this.domDivActions.appendChild(this.domLinkClose);
	},

	hide: function(event)
	{
		if (this.domDivUploader.parentNode)
			Element.remove(this.domDivUploader);

		return false;
	},

	show: function(element)
	{
		element.appendChild(this.domDivUploader);
	},

	submitForm: function(event)
	{
		this.domForm.submit();
	},

	onFrameLoad: function(event)
	{
		var iFrameDoc =  self.frames[this.domIframeName].document;


		if (iFrameDoc.location.href != 'about:blank')
		{
			var text = iFrameDoc.body.innerHTML.unescapeHTML();
			//trim text
			text = text.replace(/^\s+|\s+$/g, '');
			this.onUpload(text);
			this.hide();

		}
	},

	onUpload: function(responseText)
	{
		//alert(responseText);
	}

};
