$(document).ready(function() {
	$('#tabs').tabs();
	
	if($(".demo") && document.location.hash){
		$.scrollTo(".demo");
	}
	$(".demo ul").localScroll({ 
		target:".demo",
		duration:0,
		hash:true
	});
		
	
    $('.slideshow').cycle({
		fx: 'fade',
		speed: '1000', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
		timeout: '2000'
	});

    //change for the request list oage
	switchFilterType();
	$('#filterType').change(function(){switchFilterType();});
	
	//Jquery social bookmark 
	$('#expandedBookmark').bookmark({sites: ['delicious', 'digg', 'facebook', 'twitthis'] , compact: false})

	/*
	//this is for my gallery page
	$('.gallery_demo_unstyled').addClass('gallery_demo'); // adds new class name to maintain degradability
	
	$('ul.gallery_demo').galleria({
		history   : true, // activates the history object for bookmarking, back-button etc.
		clickNext : true, // helper for making the image clickable
		insert    : '#main_image', // the containing selector for our main image
		onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
			
			// fade in the image & caption
			if(! ($.browser.mozilla && navigator.appVersion.indexOf("Win")!=-1) ) { // FF/Win fades large images terribly slow
				image.css('display','none').fadeIn(1000);
			}
			caption.css('display','none').fadeIn(1000);
			
			// fetch the thumbnail container
			var _li = thumb.parents('li');
			
			// fade out inactive thumbnail
			_li.siblings().children('img.selected').fadeTo(500,0.3);
			
			// fade in active thumbnail
			thumb.fadeTo('fast',1).addClass('selected');
			
			// add a title for the clickable image
			image.attr('title','Next image >>');
		},
		onThumb : function(thumb) { // thumbnail effects goes here
			
			// fetch the thumbnail container
			var _li = thumb.parents('li');
			
			// if thumbnail is active, fade all the way.
			var _fadeTo = _li.is('.active') ? '1' : '0.3';
			
			// fade in the thumbnail when finnished loading
			thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
			
			// hover effects
			thumb.hover(
				function() { thumb.fadeTo('fast',1); },
				function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
			)
		}
	});
	*/
});

function switchFilterType(){
	$('.filterCon').css('display','none');
	$('#'+$('#filterType').val()).css('display','inline');
}

$('#messagefolders').tabs({
    load: function(event, ui) {
        $('a', ui.panel).click(function() {
            $(ui.panel).load(this.href);
            return false;
        });
    }
});


var swfu;
$( function() {
    swfu = new SWFUpload({
       file_post_name : "file",
       upload_url :"store/pictureUpload.do",

       //post_params: {"u" : "<security:authentication property="principal.user.id"/>"},
       
       file_size_limit :"20 MB", 
       file_types :"*.jpg;*.jpeg;",
       file_types_description :"JPG/JPEG Images",
       file_upload_limit :"1",

       file_dialog_start_handler: fileDialogStartHandler,
       file_queue_error_handler :fileQueueError,
       file_dialog_complete_handler :fileDialogComplete,
       upload_progress_handler :uploadProgress,
       upload_error_handler :uploadError,
       upload_success_handler :uploadSuccessNew,
       upload_complete_handler :uploadComplete,

       button_action : SWFUpload.BUTTON_ACTION.SELECT_FILE, 

       button_image_url : "images/upload_button.png",
       button_placeholder_id : "spanButtonPlaceholder",
       button_width: 120,
       button_height: 25,
       button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
       
       flash_url :"scripts/swfupload/swfupload.swf",

       custom_settings : {
           upload_target :"divFileProgressContainer"
       },
       
       debug :false
   });

    $('#regAlert').hide();
});

    
function uploadSuccessNew(file, serverData) {
	try {
		var progress = new FileProgress(file,  this.customSettings.upload_target);
		var strs = serverData.split("?");
		var imglink, imgid, picType;
		if(strs.length == 4){
			imglink = strs[0]+"?"+strs[1];
			imgid = strs[2];
			picType = strs[3];
			if(picType == "isref"){
	            $("#thumbnails").attr("src", imglink);
	            $("#thumbnails").css('display', 'block');
	            $("#refid").attr("value", imgid);
			}
			if(picType == "isafter"){
				addUpImage(imgid, imglink);
			}
		} else if(strs.length == 3){
			imglink = strs[0]+"?"+strs[1];
			imgid = strs[2];
			addImage(imgid, imglink);
			addOpDel();
			swfu.setButtonDisabled(true);
	        $('#regAlert').show();			
		} else {
			$("#thumbnails").attr("src", strs);
		}
        progress.setStatus("Thumbnail Created.");
		progress.toggleCancel(false);
		/*if (serverData.substring(0, 7) === "FILEID:") {
			addImage("thumbnail.php?id=" + serverData.substring(7));

			progress.setStatus("Thumbnail Created.");
			progress.toggleCancel(false);
		} else {
			addImage("images/error.gif");
			progress.setStatus("Error.");
			progress.toggleCancel(false);
			alert(serverData);

		}*/


	} catch (ex) {
		this.debug(ex);
	}
}

function addUpImageNew(id, src) {
	var newImg = document.createElement("img");
	newImg.style.margin = "5px";
	newImg.id = id;
	
	document.getElementById("selectedimgs").appendChild(newImg);
	if (newImg.filters) {
		try {
			newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;
		} catch (e) {
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
		}
	} else {
		newImg.style.opacity = 0;
	}

	newImg.onload = function () {
		fadeIn(newImg, 0);
	};
	newImg.src = src;
	newImg.id = id;
}
	/*
	$(function(){		
	    $('#upload').dialog({
	        autoOpen: false,
	    	width: 640,
	        height: 350,
	        modal: true,
	        resizable: false,
	        draggable: false,
	        buttons: { 'Done Upload' : function() { addUpImageToList(); addOpDel(); } },
	        open:function(){
	            //$(this).parents('.ui-dialog:first').find('.ui-dialog-titlebar').remove();
	        }
	    });
	
	    $('#dialog_upload').click(function(){
	        $('#thumbnails, #divFileProgressContainer').html('');
	        $('#upload').dialog('open');
	        return false;
	    });
	
	    addOpDel();
	
	});
	*/
function addOpDel(){
	$('.op-btn').hover(
		function(){
		    $(this).find('span').css('display','block');
		},
		function(){
            $(this).find('span').css('display','none');
        }
    );
    $('.op-del-btn').click(function(){
    	var imgids = $('#imgids').attr('value').split(',');
        var currentImgId = $(this).next('img').attr('id');
        var idIndex = jQuery.inArray(currentImgId, imgids);
        imgids.splice(idIndex,1);
        $("<table id='temptable' style='display:none;'></table>").appendTo("body");
        $('#temptable').html($('#selectedimgs').html());
        $('#selectedimgs').html('<tr></tr>');
        for(var i=0;i<imgids.length;i++){
            var imgId = imgids[i];
            var imgLink = $('#'+imgId).attr('src');
            addImage(imgId, imgLink);
        }
        $('#temptable').remove();
        $('#imgids').val(imgids.join(','));
        addOpDel();
		swfu.setButtonDisabled(false);
        $('#regAlert').hide();
    });
}

function addUpImageToList(){
	var ids = $("#imgids").attr("value").split(',');
    var imgs = $("#thumbnails img");
    if (imgs != null){
	    for(var i=0;i<imgs.length;i++){
	        var imgid = imgs[i].id;
	        var imglink =  imgs[i].src;
	        if(jQuery.inArray(imgid, ids) == -1) {
	        	addImage(imgid, imglink);
	        }        
	    }
    }
    $('#upload').dialog('close');
}

function addImageToList(){
    var ids = $("#imgids").attr("value").split(',');
    var imgs = $("#gallerytable img.slct-img"); 
    if (imgs != null){
	    for(var i=0;i<imgs.length;i++){
	        var imgid = imgs[i].id;
	        var imglink =  imgs[i].src;
	        if(jQuery.inArray(imgid, ids) == -1) {
	            addImage(imgid, imglink);
	        }
	    }
    }
    $('#gallery').dialog('close');
}

function fileDialogStartHandler() {
	var postParams = this.settings.post_params; 
	if ( postParams.u == null) {
		$.post('user/autoSignIn.do', 
				function(response) {
					eval('var data = '+ response);
					swfu.addPostParam("u", data.user.id);
				}
		);
	}
}

