/*
 * GalleryUI (for jQuery)
 * version: 0.0 
 * @requires jQuery v1.2 or later
 */
(function($) {
	
  $.galleryui = function(data, klass) {
    alert('first');
  }

  /*
   * Public, $.galleryui methods
   */
  $.extend($.galleryui, {
    settings: {
      galleryuiDivId      	: '#galleryui',
      galleryuiDivAllId      	: '#galleryui'
    },
    context: {
        pageCount	: 0,
        prefix: 'public',
        selectedPage: 0,
        drawImagesCallback: $.galleryui.drawImagesCallback,
        useFacebox: true,
        sharingDivId: 'none',
        galleryuiDivId: '#galleryui',
        faceboxInitialized: false,
        imagesResponseData: null
      },

    drawImagesCallback: function(response) {
    	$.galleryui.context.drawImagesCallback = $.galleryui.drawImagesCallback;
    	$.galleryui.context.pageCount = response.data.count;
    	$.galleryui.context.imagesResponseData = response.data;
    	
    	if(gallery.context["socialId"] == "all"){
    		$.galleryui.context.prefix = "all_";
    		$.galleryui.context.galleryuiDivId = $.galleryui.settings.galleryuiDivAllId;
    	}else
    	{
    		$.galleryui.context.prefix = gallery.context["socialId"]+"_";
    		$.galleryui.context.galleryuiDivId = $.galleryui.settings.galleryuiDivId;
    	}
    	
    	var idPrefix = $.galleryui.context.prefix;

    			//prepare skeleton
    			var str = "<table><tbody>"+
    				"<tr>"+"<td>"+
						"<div id='"+idPrefix+"sortingDiv' class='glr_sort_div'></div>"+
						"</td>"+"<td>"+
						"<div id='"+idPrefix+"pagingTopDiv' class='gallPaging'></div>"+
						"</td>"+"</tr>"+
    				"<tr>"+"<td colspan='2'>"+
    						"<div id='"+idPrefix+"imageDiv' class='gallImages'></div>"+
    						"<td>"+"</tr>"+
    				"<tr>"+"<td>"+"</td>"+"<td>"+
    					"<div id='"+idPrefix+"pagingBottomDiv' class='gallPaging'></div>"+
    						"</td>"+"</tr>"+"</tbody></table>";
    			
    			
    			$($.galleryui.context.galleryuiDivId).html(str);
    			
    			drawImages(response.data);
    			drawSortOrders();
    			drawPaging();
    },
    voteCallback: function(response){
		//get prefix from somewhere
		idPrefix = $.galleryui.context.prefix;
	    var voted = response.data.voted;
	    var itemId = response.data.itemId;
	    if (voted) {
	        document.getElementById("loading_" + itemId).innerHTML = "Your voice has been counted";
			var voteSpan=document.getElementById(idPrefix+"vote_"+response.data.itemId).childNodes.item(1);
			var oldCount=parseInt(voteSpan.nodeValue);
			voteSpan.nodeValue=oldCount+1;
	    }
	    else {
	        document.getElementById("loading_" + itemId).innerHTML = "You have already voted";
	    }
		var expToCall="document.getElementById(\'loading_"+ itemId+"\').innerHTML=''";
		var t = setTimeout(expToCall, 3000);
	},
	 commentCallback: function(response){
		
		var images = $.galleryui.context.imagesResponseData.images;
		
		//fetch current image id
		var srcArray = $('#facebox .image img').attr('src').split("/");
		var imgId = srcArray[srcArray.length-2];
		if(imgId == undefined || imgId == null){
			return;
		}
		var img = null;
		//update cached infor
		for (var i = 0; i < images.length; i++) {
			if(images[i].id == imgId){
				images[i] = response.data.item;
				img = images[i];
			}
		}
		
		buildItemInfoDiv(img);
	},
	shareCallback: function(response){
		//get prefix from somewhere
		idPrefix = $.galleryui.context.prefix;
	    var shared = response.data.RESPONSE_CODE;
	    var itemId = response.data.itemId;
	    var shareDiv = document.getElementById($.galleryui.context.sharingDivId);
	    
	    if (shared=="shared") {
	        document.getElementById("loading_" + itemId).innerHTML = "Image shared!";
	        shareDiv.innerHTML = "Unshare";
	        shareDiv.attributes.getNamedItem("image_shared").value = "1";
	    }
	    else if (shared=="unshared") {
	        document.getElementById("loading_" + itemId).innerHTML = "Image unshared!";
	        shareDiv.innerHTML = "Share";
	        shareDiv.attributes.getNamedItem("image_shared").value = "0";
	    }
	    else {
	        document.getElementById("loading_" + itemId).innerHTML = "Sharing is not permitted to you!";
	    }

		var expToCall="document.getElementById(\'loading_"+ itemId+"\').innerHTML=''";
		var t = setTimeout(expToCall, 3000);
	},
	
	drawUploaderSimple: function(uploaderContentDivId){
		var buttonSaveId = "mySaveButton";
		var buttonSaveAndPublishId = "mySaveAndPublishButton";
		var str = "";
	    str += '<div>'+
	    				'<form name="galleryui_upload_simple" id="galleryui_upload_simple" enctype="MULTIPART/FORM-DATA" method="post" action="/gallery/'+gallery.itemTypes[gallery.context["itemType"]]+'/upload-simple" >'+
							'<input type="hidden" id="galleryui_upload_simple_uploadToken" value="'+gallery.context["socialId"]+'_'+gallery.generateUploadToken()+'" name="uploadToken"/>'+
							'<input type="hidden" id="galleryui_upload_simple_model_publish" value="'+Gallery.UNPUBLISHED_KEY+'" name="model.status"/>'+
							'<input type="hidden" id="galleryui_upload_simple_model_user_socialId" value="'+gallery.context["socialId"]+'" name="model.user.socialId"/>'+
							'<input type="hidden" id="galleryui_upload_simple_model_user_socialName" value="'+gallery.context["socialName"]+'" name="model.user.socialName"/>'+
							'<input type="hidden" id="galleryui_upload_simple_model_user_socialProfile" value="'+gallery.context["socialProfileUrl"]+'" name="model.user.socialProfileUrl"/>'+
							'<input type="hidden" id="galleryui_upload_simple_model_user_socialThumbUrl" value="'+gallery.context["socialThumbUrl"]+'" name="model.user.socialThumbUrl"/>'+
							'<input type="hidden" id="galleryui_upload_simple_model_user_socialType" value="'+gallery.context["socialType"]+'" name="model.user.socialType"/>'+
							'<input type="hidden" id="galleryui_upload_simple_model_itemType" value="'+gallery.context["itemType"]+'" name="model.itemType"/>'+
							'<input type="hidden" id="galleryui_upload_simple_model_category" value="'+gallery.context["category"]+'" name="model.category"/>'+
							'<input type="hidden" id="galleryui_upload_simple_model_source" value="'+gallery.context["source"]+'" name="model.source"/>'+
							
							'<input type="text" name="model.title" value="" id="galleryui_upload_simple_model_title"/>'+
							'<input type="file" id="galleryui_upload_simple_file" value="" name="file"/>'+
							'<input type="submit" class="class java.util.HashMap" value="Upload" name="SubmitButton" id="galleryui_upload_simple_submit"/>'+
						'</form>'+
				'</div>';
		document.getElementById(uploaderContentDivId).innerHTML=str;
		var options = {
					success: afterUploadCallbackJson,
					dataType:  'json',
					type: 'post',
					clearForm: true,
					beforeSubmit: beforeUploadValidate 
		};
	   	$('#galleryui_upload_simple').ajaxForm(options);
	},//end drawUploaderSimple

	drawUploaderFlash: function(uploaderContentDivId){
		var str = "";
		
	    str += '<div id="uploadWighFalshContent">'+
							    	'<h2 class="text">Please Download Flash Player.</h2>'+
							           '<p><a target="_blank" href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get AdobeFlash player" /></a></p>'+
							    '</div>';
		document.getElementById(uploaderContentDivId).innerHTML=str;
		
		$(document).trigger('galleryui.loadFlash');
	}//end drawUploaderFlash
  })

  /*
   * Public, $.fn methods
   */

  $.fn.galleryui = function(settings) {
    init(settings)

    function clickHandler() {
      alert('clickHandler');
      return false
    }

    //return this.click(clickHandler)
  }

  /*
   * Private methods
   */
   // called one time to setup galleryui on this page
   function init(settings) {
     if ($.galleryui.settings.inited) return true
     else $.galleryui.settings.inited = true
     
     if($.galleryui.context.useFacebox && $.galleryui.context.faceboxInitialized){
    	 $.facebox.settings.loadingImage = 'js/facebox/loading.gif';
    	 $.facebox.settings.closeImage = 'js/facebox/closelabel.gif';
     }

     //if(!gallery) alert('Gallery object is missing!');
     //$(document).trigger('init.galleryui')
     
     if (settings) $.extend($.galleryui.settings, settings)
    // $('body').append($.galleryui.settings.galleryuiHtml)

   }
   
   var drawImages = function(data){
		//get prefix from somewhere
		idPrefix = $.galleryui.context.prefix;
		
		var str = "";
	    var images = data.images;
	    var count = data.count;
	    str += "<table cellPadding=0 cellspacing=3><tbody>";
	    var currentImage = "";
	    for (var i = 0; i < images.length; i++) {
	        currentImage = images[i];
	        if (i % COL_COUNT == 0) {
	            str += "<tr>";
	        }
	        str+="<td class='glr_images_border'>"+
					"<table width='120px'><tbody>"+
						"<tr>"+
							"<td style='text-align:center; height: 100px; width:100px'>"+
								"<a href='" + GALLERY_SERVER_URL+"images/" + currentImage.id + "/medium"+"' rel='galleryui_facebox' title='"+currentImage.title+"'  >"+
									"<img id='"+idPrefix+"image_"+i+"' class='glr_images_img' style='cursor:pointer;' src='" + GALLERY_SERVER_URL+"images/" + currentImage.id + "/small"+
									"' image_id='"+currentImage.id+
									"' image_published='"+currentImage.published+
									"' alt='loading...'/>"+
								"</a>"+	
								"<div id='"+idPrefix+"_image_"+i+"' style='display:none' "+
									"src='" + GALLERY_SERVER_URL+"images/" + currentImage.id + "/medium"+"' "+
									"image_id='"+currentImage.id+"' "+
									"image_published='"+currentImage.published+"' "+
									"image_views='"+currentImage.owner.viewCount+"' "+
									"ownerId='"+currentImage.owner.ownerId+"' "+
									"ownerSocialId='"+currentImage.owner.ownerSocialId+"' "+
									"ownerSocialName='"+currentImage.owner.ownerSocialName+"' "+
									"ownerProfileUrl='"+currentImage.owner.ownerProfileUrl+"' "+
									"ownerSocialTumbUrl='"+currentImage.owner.ownerSocialTumbUrl+"' "+
									"ownerSocialType='"+currentImage.owner.ownerSocialType+"' >"+
								"</div>"+
								"<div id='"+idPrefix+"image_"+i+"_tags' style='display:none'>"+currentImage.tags+"</div>"+
								
							"</td>"+
				        "</tr>"+
						"<tr>"+
							"<td>"+
								"<span class=''><span class='glr_images_info'>Title:&nbsp</span> "+currentImage.title+"</span>"+
							"</td>"+
						"</tr>"+
						"<tr>"+
							"<td>"+
								"<span class='' id='"+idPrefix+"vote_"+currentImage.id+"'>"+
								"<span class='glr_images_info'>Votes:&nbsp;</span>"+currentImage.voteCount+"</span>"+
								"<span ><img id='"+idPrefix+"vote_"+i+"' title='Vote for Image' image_id='"+currentImage.id+"' src='"+GALLERY_SERVER_URL+"img/vote.png' class='glr_images_vote_icon'/></span>"+
							"</td>"+
						"</tr>"+
						"<tr>"+
							"<td>"+
								"<span class='' id='"+idPrefix+"view_"+currentImage.id+"'>"+
								"<span class='glr_images_info'>Views:&nbsp;</span>"+currentImage.viewCount+"</span>"+
							"</td>"+
						"</tr>"+
						"<tr>"+
						"<td>"+
							"<div id='"+idPrefix+"share_"+i+"' class='glr_images_action' title='share' image_id='"+currentImage.id+"' image_shared='"+currentImage.published+"' style='cursor: pointer;'>"+(currentImage.published == 1 ? "Unshare" : "Share")+"</div>"+
						"</td>"+
					"</tr>"+
						"<tr>"+
							"<td>"+
								"<div class='small_message' id='loading_"+currentImage.id+"'></div>"+
							"</td>"+
						"</tr>"+
					"</tbody></table>"+
				"</td>";
	        
			if (i % COL_COUNT == COL_COUNT - 1) {
	            str += "</tr>";
	        }
	    }
	    str += "</tbody></table>";
	    var imageDiv = document.getElementById(idPrefix+"imageDiv");
	    imageDiv.style.width = COL_COUNT*160+"px";
	    imageDiv.style.height = PAGE_LIMIT/COL_COUNT*200+"px";
	    imageDiv.innerHTML = str;
	    
		
		for(var i = 0; i < images.length; i++){
			var image = document.getElementById(""+idPrefix+"image_"+i);
			
			if(image && !$.galleryui.context.useFacebox){
				image.onclick = function(){
					galleryClickCallback(this.getAttribute("id"));
				}
			}
			var vote = document.getElementById(""+idPrefix+"vote_"+i);
			if(vote){
				vote.onclick = function(){
								itemId = this.getAttribute("image_id");
								document.getElementById("loading_" + itemId).innerHTML="<img src='"+GALLERY_SERVER_URL+"img/ajax-loader.gif'";
								
								gallery.vote(itemId, $.galleryui.voteCallback, 1);
						       }
			}
			var share = document.getElementById(""+idPrefix+"share_"+i);
			if(share){
				share.onclick = function(){
								itemId = this.getAttribute("image_id");
								document.getElementById("loading_" + itemId).innerHTML="<img src='"+GALLERY_SERVER_URL+"img/ajax-loader.gif'";
								shared = this.getAttribute("image_shared");
								$.galleryui.context.sharingDivId = this.getAttribute("id");
								if(shared == 1){
									gallery.unshare(itemId, $.galleryui.shareCallback);
								}else{
									gallery.share(itemId, $.galleryui.shareCallback);
						       }
							}
			}
//			var addComment = document.getElementById('#glr_add_comment_command_'+images[i].id);
//			if(addComment){
//				addComment.onclick = function(){
//					alert('send save comment request');
//							}
//			}
//			$('#glr_add_comment_command_'+images[i].id+'').click(function(){
//				alert('send save comment request');
//			});
		}
		
		if($.galleryui.context.useFacebox){
			$.facebox.settings.imageTypes = [ 'png', 'jpg', 'jpeg', 'gif', 'small', 'medium' ];
			$('a[rel*=galleryui_facebox]').facebox({});
			if(!$.galleryui.context.faceboxInitialized){
				$('#facebox .content').empty().after('<div class="info"></div>');
				$.galleryui.context.faceboxInitialized = true;
			}
			
		}
		
		
	}//end drawImages

	var drawSortOrders = function(){
		
		//get prefix from somewhere
		idPrefix = $.galleryui.context.prefix;
		var str = "";
		var index = 0;
		var sortOrders = gallery.getSupportedSortOrders(); 
		var currentSort = gallery.getSortOrder(); 
		for(var i in sortOrders){
			if(i == currentSort){
				str += "<span class='glr_sort glr_sort_active'>"+sortOrders[i]+"</span>";
			}
			else{
				str += "<span id='"+idPrefix+"_sort_order_"+index+"' sort='"+i+"' class='glr_sort'>"+sortOrders[i]+"</span>"
			}
			str += "|";
			index++;
		}
		document.getElementById(idPrefix+"sortingDiv").innerHTML=str;
		
		var index = 0;
		for(var i  in sortOrders){
			var order = document.getElementById(idPrefix+"_sort_order_"+(index++));
			if(order){
				order.onclick = function(){
									//reset paging
									galleryContext["selectedPage"] = 0;
									
									gallery.setSortOrder(this.getAttribute("sort"));
									//redraw
									drawSortOrders();
									//page if null will start from first page
									//published if null will use currect published state
									//callbackMethod take from context
									callbackMethod = $.galleryui.drawImagesCallback;
									gallery.getItems(null, null, callbackMethod);
								}
			}
		}
	}//end drawSortOrders
	
	var drawPaging = function(){
		
		var selectedPage = null;
		if($.galleryui.context.selectedPage == 'undefined' || $.galleryui.context.selectedPage==null){
			selectedPage = 0;
			$.galleryui.context.selectedPage = 0;
		}else
		{
			selectedPage = $.galleryui.context.selectedPage;
		}
		var count = typeof $.galleryui.context.pageCount == 'undefined' || $.galleryui.context.pageCount==null ? 0 : $.galleryui.context.pageCount;
		idPrefix = $.galleryui.context.prefix;
		var PAGING_RANGE=3;
	
		var str = '<div>';
	    var pageCount = Math.ceil(count / PAGE_LIMIT);
		var inf = Math.floor(selectedPage/PAGING_RANGE)*PAGING_RANGE; 
		var sup = (Math.floor(selectedPage/PAGING_RANGE)+1)*PAGING_RANGE;
		if(inf > 0){
			str += '&nbsp;<a class="glr_page" id="'+idPrefix+'_paging_first">1</a>';
		}
	    if (selectedPage > 0){
	        str += '&nbsp;<a class="glr_page" id="'+idPrefix+'_paging_prev"  selectedPage="'+selectedPage+'">&lt;</a>';
	    }
	    
	    var index = 0;
	    for (var i = inf; i < sup; i++) {
	        if (pageCount >= i + 1) {
				if(selectedPage != i){
					str += '&nbsp;<a class="glr_page" id="'+idPrefix+'_paging_'+index+'" page="'+i+'" index="'+index+'">' + (i + 1) + '</a>';
				}else{ 
					str += "&nbsp;<span class='glr_page_active'>"+(i+1)+"</span>";
				}
				index++;
			}
	    }
	    if (selectedPage < pageCount - 1) {
	        str += '&nbsp;<a class="glr_page" id="'+idPrefix+'_paging_next" selectedPage="'+selectedPage+'">&gt;</a>';
	    }
		
		if(sup < pageCount){
	        str += ' of <a class="glr_page" id="'+idPrefix+'_paging_last" pageCount="'+pageCount+'">'+pageCount+'</a>';
		}
	    str += '</div>';
	    $($.galleryui.context.galleryuiDivId+ " #"+idPrefix+"pagingTopDiv").html(str);
	    //$($.galleryui.context.galleryuiDivId+ " #"+idPrefix+"pagingBottomDiv").html(str);
	    
	    var paging_first = document.getElementById(idPrefix+"_paging_first");
		if(paging_first){
			paging_first.onclick = function(){
									$.galleryui.context.selectedPage = 0;
									//page if null will start from first page
									//published if null will use currect published state
									//callbackMethod take from context
									callbackMethod = $.galleryui.drawImagesCallback;
									gallery.getItems(0, null, callbackMethod);
								}
		}
		var paging_prev = document.getElementById(idPrefix+"_paging_prev");
		if(paging_prev){
			paging_prev.onclick = function(){
				$.galleryui.context.selectedPage = $.galleryui.context.selectedPage-1;
									//page if null will start from first page
									//published if null will use currect published state
									//callbackMethod take from context
									callbackMethod = $.galleryui.drawImagesCallback;
									gallery.getItems(parseInt(this.getAttribute("selectedPage"))-1, null, callbackMethod);
								}
		}
		for(var i = 0; i < PAGING_RANGE; i++){
			var paging = document.getElementById(idPrefix+"_paging_"+i);
			if(paging){
				paging.onclick = function(){
					$.galleryui.context.selectedPage = parseInt(this.getAttribute("page"));
									//page if null will start from first page
									//published if null will use currect published state
									//callbackMethod take from context
									callbackMethod = $.galleryui.drawImagesCallback;
									gallery.getItems(this.getAttribute("page"), null, callbackMethod);
								}
			}
		}
		var paging_next = document.getElementById(idPrefix+"_paging_next");
		if(paging_next){
			paging_next.onclick = function(){
				$.galleryui.context.selectedPage = $.galleryui.context.selectedPage+1;
									//page if null will start from first page
									//published if null will use currect published state
									//callbackMethod take from context
									callbackMethod = $.galleryui.drawImagesCallback;
									gallery.getItems(parseInt(this.getAttribute("selectedPage"))+1, null, callbackMethod);
								}
		}
		var paging_last = document.getElementById(idPrefix+"_paging_last");
		if(paging_last){
			paging_last.onclick = function(){
				$.galleryui.context.selectedPage = parseInt(this.getAttribute("pageCount"))-1;
									//page if null will start from first page
									//published if null will use currect published state
									//callbackMethod take from context
									callbackMethod = $.galleryui.drawImagesCallback;
									gallery.getItems(parseInt(this.getAttribute("pageCount"))-1, null, callbackMethod);
								}
		}
	}//end drawPaging
	
	var buildItemInfoDiv = function(img){
	
		var str = "<div id='image_info_"+img.id+"' style='display:block' >"+
			"<span class='glr_images_info'>Title:&nbsp</span> <span class='glr_images_info_text'>"+img.title+"</span><br/>"+
			"<span class='glr_images_info'>Votes:&nbsp;</span><span class='glr_images_info_text'>"+img.voteCount+"</span><br/>"+
			"<span class='glr_images_info'>Comments:&nbsp;</span><br/><hr width='50%'/>";
			for (var ii = 0; ii < img.comments.length; ii++) {
					str+="<div class='glr_images_info_text'>"+img.comments[ii].commentBody+"</div><br/>"+
					"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class='glr_images_info'>Author:&nbsp;</span>"+
					"<img src='"+img.comments[ii].commentAuthorSocialThumbUrl+"' style='width:40px' /><hr width='50%'/>";
			}
			str+="<textarea id='glr_add_comment_text_"+img.id+"' rows='3' cols='30'> </textarea>"+
			"<span id='glr_add_comment_command_"+img.id+"' class='glr_images_action' >Add Comment</span>"+
			"</div>";
			
			$('#facebox .info').empty().html(str);
			$('#facebox #glr_add_comment_command_'+img.id).click(function(){
				var comment = $('#facebox #glr_add_comment_text_'+img.id).val().trim();
				if(comment != ''){
					gallery.comment(img.id, $.galleryui.commentCallback, html_sanitize(comment, 
							function urlX(url) { /*if(/^https?:\/\//.test(url)) { return url }*/ }, 
							function idX(id) { return id }));
				}
				
			});
	}
	

  /*
   * Bindings
   */
	$(document).bind('reveal.facebox', function() { 
		
		var srcArray = $('#facebox .image img').attr('src').split("/");
		var imgId = srcArray[srcArray.length-2];
		
		var images = $.galleryui.context.imagesResponseData.images;
		var img = null;
		//update cached infor
		for (var i = 0; i < images.length; i++) {
			if(images[i].id == imgId){
				img = images[i];
			}
		}
		
		buildItemInfoDiv(img);
	});



})(jQuery);
