//coded by Phuc Nguyen

//Email: phnguyen@gmail.com

//Edited 10/25/2010

//NOSELECT PLUGIN

$(function(){
    $.extend($.fn.disableTextSelect = function() {
        return this.each(function(){
            if($.browser.mozilla){//Firefox
                $(this).css('MozUserSelect','none');
            }else if($.browser.msie){//IE
                $(this).bind('selectstart',function(){return false;});
            }else{//Opera, etc.
                $(this).mousedown(function(){return false;});
            }
        });
    });
    $('.noselect').disableTextSelect();//No text selection on elements with a class of 'noSelect'
});
//END OF NOSELCT PLUGIN

$('document').ready(function(){
	var self = this;
	self.HOST = "http://e-d-and-i.com/";
	var el = $('.slideshow .content');
	var curr = 0;
	var slidesInterval; 
	if(el){
		$.ajax({
			url:'includes/getProjects_json.php',
			success:function(data){
				var json = eval('('+data+')');
				runSlideShows(json,0);
			}
		});
	}
	
	$('.project:odd').addClass('highlighted');
	$('.minigallery_list li a').lightBox();
	$('a.preview').lightBox();
	$('#extend_menu_title').click(function(){
			$('#extend_content').toggle('fast');
   });
	$('.table_list tr:even').addClass('odd');

	 $('#photo_uploader').uploadify({
			'swf'  : 'js/uploadify/uploadify.swf',
			'uploader'    : 'js/uploadify/uploadify.php',
			'cancelImage' : 'js/uploadify/uploadify-cancel.png',
			'checkExisting':'js/uploadify/uploadify-check-existing.php',
			'folder'    : 'js/uploadify/temp',
			'auto'      : true,
			'buttonText':'SELECT PHOTOS',
			'fileTypeDesc'    : 'Images (JPG, PNG)',
			'fileTypeExts'    : '*.jpg;*.png',
			'postData':{folder:'/temp',
						file_type:'png,jpg'},
			'multi':true,
			'onUploadComplete':function(){
				self.get_files('temp_file_container',$("#main_path").val());
			}
	});

	try{
    tinyMCE.init({
        // General options
            mode : "textareas",
            theme : "advanced",
			elements : 'nourlconvert',
            plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
            // Theme options
            theme_advanced_buttons1 : "save,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,|,cut,copy,paste,pastetext,pasteword,",
            theme_advanced_buttons2 : "code,|,search,replace,|,bullist,numlist,|,undo,redo,|,link,unlink,anchor,image,|,insertdate,inserttime,preview,|,spellchecker,|,insertfile,insertimage",
            theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : true,
    
            // Skin options
            skin : "o2k7",
            skin_variant : "silver",
            extended_valid_elements : "img[src|width|height|class|id|style],a[href|class|id|target],iframe[src,width,height],p",
            // Example content CSS (should be your site CSS)
            // Drop lists for link/image/media/template dialogs
            template_external_list_url : "js/template_list.js",
            external_link_list_url : "js/link_list.js",
            external_image_list_url : "js/image_list.js",
            media_external_list_url : "js/media_list.js",
            
    });}catch(ex){}//ignore it

	//Start copy code from here
	//-----copy here-----
	//task 1: link partner's image
	//---------------copy from here--- -- - - - -   
	if($(".partner")){
		 $(".partner").each(function(index,el){
					$(el).click(function(e){
						  e.preventDefault();
						  var l = $(this).find("a");
						  if(l) var url = $(l).attr("href");
						  if(url.length>0) window.open(url);
					});
		 });
	}
	//--- -- - - - - End of function - - - - --  

	//task2: link image from slide show
	
	//----copy from here------
	
	if($(".box .content")){
	
		 var slides = $(".box .content");
	
		 $(slides).each(function(index, el){
	
			   $(el).click(function(e){
	
					  var tar = e.target;
	
					  if(tar && $(tar).hasClass("project_images")){
	
							   var li = $(tar).parent().find("span#link a");
	
							   if(li && $(li).attr("href").length>0){ 
	
									e.preventDefault();
	
									window.location.replace($(li).attr("href"));
	
							   }
	
					  }
	
			   })
	
		 });
	
	}
	
	//------end here------------



	//task3: link images in project list'
	
	//--------code start here------
	
	if($(".project")){
	
		$(".project").each(function(index,el){
	
			  $(el).bind("click",function(e){
					var tar = e.target;
					 if(tar && $(tar).hasClass("project_image")){
						  var l = $(this).find("span#link a");
	
						  if(l && $(l).attr("href").length>0){
	
							   e.preventDefault();
	
							   window.location.replace($(l).attr("href"));
	
						  }
	
					 }
	
			  });
	
		 });
	
	}
///end of copy code

//===========================================================================
//GALLERY INTERFACE
//===========================================================================
	self.url_list = {temp:{key:"temp",
							 path:"js/uploadify/temp"},
						gallery:{key:"gallery",
								path:"images/gallery"}};
	self.get_files = function(id,path){
		var container = $("#" + id);
		if(container.length>0){
			$.ajax({
				type:"POST",
				url:'includes/get_uploaded_files.php',
				data:{folder:path},
				success:function(d){
					var file_list_json = eval('('+d+')');
					var string_list = Array();
					var is_first = true;
					string_list[string_list.length] = '<ul class="temp_file_list">';
					$.each(file_list_json,function(index,val){
						string_list[string_list.length]= '<li class="temp_file" rel="';
						string_list[string_list.length]=val;
						string_list[string_list.length]='">';
						string_list[string_list.length]=val ;
						string_list[string_list.length]='</li>';
					});	
					string_list[string_list.length] = '</ul>';
					$(container).html(string_list.join(''));
				}
			});	
		}
	};
	
	
	//handle actions panel
	$(".actions").live("click",function(e){
			var rel = $(this).attr("rel");
			var opts = {select_all:'select_all',
							deselect_all:'deselect_all',
							delete_all:'delete_all',
							delete_selected:'delete_selected',
							add_to_album:'add_to_album',
							mini_gallery_next_page:"mini_gallery_next",
							mini_gallery_previous_page:"mini_gallery_previous"};
			if(rel.length>0){
				var file_list;
				if(rel.localeCompare(opts.select_all)==0){
					file_list = $(".temp_file");
					if(file_list.length>0){
						$.each(file_list,function(index, e){
							if(!$(e).hasClass("selected")) $(e).addClass("selected");
						});
					}
				}else if(rel.localeCompare(opts.delete_selected)==0){
					file_list = $(".temp_file");
					if(file_list.length>0){
						//get selected list
						var selected = Array();
						$.each(file_list,function(index,e){
							$(e).hasClass("selected")?selected[selected.length] = $(e).text():null;
						});
						if(selected.length>0){
							if(confirm("Are you sure to delete the following files:\n" + selected.join('\n'))){
								//call delete function
								$.ajax({
									type:"POST",
									url:'includes/delete_files.php',
									data:{file_list:selected.join('|'),
										  opt:'delete_selected',
										  path:$("#main_path").val(),
										  key:$("#main_path").attr("rel")},
									success:function(e){
										self.get_files('temp_file_container',$("#main_path").val()); //run once	
									}
								});
							}	
						}
					}
				}else if(rel.localeCompare(opts.deselect_all)==0){
					file_list = $(".temp_file");
					if(file_list.length>0){
						$.each(file_list,function(index, e){
							if($(e).hasClass("selected")) $(e).removeClass("selected");
						});
					}
					$("#temp_gallery_image_preview").remove();
				}else if(rel.localeCompare(opts.delete_all)==0){
					file_list = $(".temp_file");
					if(file_list.length>0){
						if(confirm("Are you sure to delete ALL Temp Files:\n")){
							//call delete function
							$.ajax({
								type:"POST",
								url:'includes/delete_files.php',
								data:{	opt:'delete_all',
										path:$("#main_path").val(),
										key:$("#main_path").attr("rel")},
								success:function(e){
									var response = eval('('+e+')');
									alert(response.message);
									self.get_files('temp_file_container',$("#main_path").val()); //run once	
									
								}
							});
						}	
					}
					
				}else if(rel.localeCompare(opts.add_to_album)==0){
					//check selected file
					var selected_files = $(".temp_file.selected");
					if(selected_files.length>0){
						//send this list
						var str_data = Array();
						$.each(selected_files,function(i,val){
							str_data[str_data.length] = $(val).attr("rel");
						});
						$.ajax({
							type:"POST",
							url:'includes/move_to_album.php',
							data:{data:str_data.join("|"),
									from_path:'js/uploadify/temp/',
									to_path:'images/gallery/'},
							success:function(d){
								var res = eval('('+d+')');
								if(res.success){
									
								}else{
									
								}
								alert(res.message);	
								//refresh temp folder
								self.get_files('temp_file_container',$("#main_path").val()); //run once	
							}
						});	
					}
					return false;
				}else if(rel.localeCompare(opts.mini_gallery_next_page)==0){
					var current_el =$(".minigallery_list li.selected"); 
					var next = $(current_el).next();
					if(next.length==0){
						//get the first one
						var mini_list = $(".minigallery_list li");
						next = mini_list[0];
					}
					 $(".minigallery_list li.selected").removeClass("selected");
					 $(next).addClass("selected");
					 return false;
					
				}else if(rel.localeCompare(opts.mini_gallery_previous_page)==0){
					var current_el = $(".minigallery_list li.selected");
					var prev = $(current_el).prev();
					if(prev.length==0){
						var mini_list = $(".minigallery_list li");
						prev = mini_list[mini_list.length - 1];
					}
					 $(".minigallery_list li.selected").removeClass("selected");
					 $(prev).addClass("selected");
					return false;
				}
			}//if not then do nothing
			return false;
	});
	
	self.get_files('temp_file_container',$("#main_path").val()); //run once
	$(".temp_file").live("click",function(e){
			var is_multi = true;
			if($("#multiple_file_check").attr("checked")==false){
				$(".temp_file").removeClass("selected");
				is_multi=false;
			}
			if($(this).hasClass("selected")){
				$(this).removeClass("selected");
			}else{
				$(this).addClass("selected");	
				//preview this
				var display = $("#temp_gallery_image_preview");
				if(display.length==0){
					$("#temp_file_container_wrapper").prepend("<div id='temp_gallery_image_preview'></div>");	
				}
				var img = new Image;
				img.src = self.HOST+$("#main_path").val()+"/"+$(this).attr("rel");
				var width = 200;
				var height = Math.floor(img.height * (width/img.width));
				var margin_left = 0;
				var margin_top = Math.floor((width-height)/2);
				$("#temp_gallery_image_preview").html("<img style='margin:"+margin_top+"px "+margin_left+"px;width:"+width+"px;height:"+height+"px' src='"+self.HOST+$("#main_path").val()+"/"+$(this).attr("rel")+"'>"); 
			}	
			
			return false;		
	}).live("dblclick",function(e){
		var ori_name = $(this).attr("rel");
		var rel = ori_name.split(".");
		var ext = $(this).attr("rel").split(".").pop();
		rel.pop();
		var name = rel.join("");
		$(this).html("<input id='input_rename' style='width:100px;border:0px; padding:10px;font:11px arial;' type='text' value='"+name+"' old='"+ori_name +"' ext='"+ext+"'/>");	
		var input_rename = $("#input_rename");
		if(input_rename.length>0){
			$("#input_rename").bind("keypress",function(e){
				var current_input = $(this);
				var li_ele = $(this).parent();
				//enter key detected
				if(e.keyCode==13){
					//save file name
					//check if new file name different from old one?
					var newname = $(this).val() + "." + $(this).attr("ext");
					$.ajax({
						type:"POST",
						url:"includes/rename.php",
						data:{	new_name:newname, //do not allow changing extension
								old_name:$(this).attr("old"),
								path:$("#main_path").val(),
								rel:$("#main_path").attr("rel")
						},
						success:function(res){
							var response = eval('(' + res + ')');
							//handle response
							if(response.success==true){
								//switch to new name	
								$(li_ele).html(response.new_name);
							}else{
								//restore old name
								$(li_ele).html(response.old_name);
							}
							$(li_ele).removeClass("selected");
							alert(response.message);
						}	
					});
				}
			});
		}
		
		return false;
	});
	
	//handle switch view
	$("#path_select").live("change",function(e){
		
		if($(this).val().localeCompare(self.url_list.temp.key)==0){
			$("#main_path").val(self.url_list.temp.path).attr("rel",self.url_list.temp.key);
			$("#upload_form").show();				
		}else if($(this).val().localeCompare(self.url_list.gallery.key)==0){
			$("#main_path").val(self.url_list.gallery.path).attr("rel",self.url_list.gallery.key);
			$("#upload_form").hide();
		}
		self.get_files('temp_file_container',$("#main_path").val()); 
	});	
	
//===========================================================================
//END OF GALLERY INTERFACE
//===========================================================================

});

var slideShowTimeout;

function runSlideShows(j,curr){

	if(slideShowTimeout) clearTimeout(slideShowTimeout);

	curr = (curr==j.length)?0:curr;

	var title = j[curr].title;

	var subtitle = j[curr].subtitle;

	var brief = j[curr].blurb.substring(0,500) + " ...";

	var image_link = "images/post/" + j[curr].image_link;

	var date_created = j[curr].date_created;

	var html = "";

	html = "<img src="+image_link+

			" class='project_images floatright'/><h1>"+title+

			"</h1><span class='subtitle'>"+subtitle+

			"</span><p>"+brief+

			"</p><span id='link'><a href='readmore.php?id="+j[curr].id+

			"'><img src='images/btnMore.png'/></a></span>";

	updateSlideLink(j,curr);

	$('.slideshow .content').html(html);

	$('.slideshow .content').fadeTo("slow",1,function(){

			slideShowTimeout = setTimeout(function(){

								$('.slideshow .content').fadeTo("slow",0,function(){

									runSlideShows(j,++curr);												  

								});

								},10000);

	});	

}

function updateSlideLink(j,curr){

	$('div#slideNumber').html("");

	var elStr = "";

	for(var i=0;i<j.length;i++){
		if(i==curr){
			elStr = "<div>"+(i+1)+"</div>";

			$(elStr).appendTo('div#slideNumber').addClass('selected');

		}

		else{

			elStr = "<div>"+(i+1)+"</div>";	

			$(elStr).appendTo('div#slideNumber').bind('click',slideNumberClick_handler(j,i));

		}

	}return false;

}



function slideNumberClick_handler(j,i){

	return function(){

		//turn off window.slideTimeout

		if(slideShowTimeout) clearTimeout(slideShowTimeout);

		runSlideShows(j,i);

	};	

}



