/**
 * --------------------------------------------------------------------------------
 * @desc Initialization Scripts (in most cases using livequery)
 *  
 * --------------------------------------------------------------------------------
 */
jQuery(function($){

    if(typeof $.livequery == 'function' && typeof $.fn.ajaxSubmit == 'function'){
    	$('.library_form_ajax_submit').livequery(function(){
    		library.fn.prepareform($(this));
    	});
    } else {
        $('.library_form_ajax_submit').live('submit', function(){
            library.fn.prepareform($(this));
            $(this).submit();
        });
    }
    
    if(typeof $.livequery == 'function' && typeof $.fn.ajaxSubmit == 'function'){
        $('.library_form_submit').livequery('submit', function(){
            var returnValue = true;
            if ($(this).attr('onBeforeSubmit') !='' && typeof($(this).attr('onBeforeSubmit'))!='undefined'){
                var formObject = $(this);
                returnValue = eval($(this).attr('onBeforeSubmit') + '(formObject);');
                
                if (typeof(returnValue) == 'undefined'){
                    returnValue = false;
                }
            }
            
            return returnValue;
        });
    } else {
        $('.library_form_submit').live('submit', function(){
            var returnValue = true;
            if ($(this).attr('onBeforeSubmit') !='' && typeof($(this).attr('onBeforeSubmit'))!='undefined'){
                var formObject = $(this);
                returnValue = eval($(this).attr('onBeforeSubmit') + '(formObject);');
                
                if (typeof(returnValue) == 'undefined'){
                    returnValue = false;
                }
            }
            
            return returnValue;
        });
    }
    
    if(typeof $.livequery == 'function' && typeof $.fn.watermark == 'function'){
    	$(':input[library_watermark_text]').livequery(function(){
                    if ($(this).attr('library_watermark_text') != '' && typeof($(this).attr('onBeforeSubmit'))!='undefined'){
            		$(this).watermark('library_watermark', $(this).attr('library_watermark_text'));
                    }
    	});
    }
    
   
    if(typeof $('.library_ckeditor').ckeditor == 'function'){
    	$('.library_ckeditor').ckeditor( function() 
    										{ /* callback code */ }, 
    										{ height: '350' });
    }
    
    if (typeof $('.library_validate').validator == 'function'){
    	//adds an effect called "wall" to the validator
    	$.tools.validator.addEffect("wall", function(errors, event) {

    		// get the message wall
    		var wall = $(this.getConf().container).fadeIn('slow');
    		
    		// remove all existing messages
    		wall.find("p").remove();
    		
    		// add new ones
    		$.each(errors, function(index, error) {
    			if (error.input.attr("caption") != ''){
    				wall.append(
    						"<p><strong>" +error.input.attr("caption")+ "</strong> - " +error.messages[0]+ "</p>"
    				);		
    				
    			} else {
    				wall.append(
    						"<p><strong>" +error.input.attr("name")+ "</strong> - " +error.messages[0]+ "</p>"
    				);		
    				
    			}
    		});
    		
    	// the effect does nothing when all inputs are valid	
    	}, function(inputs)  {
    		
    	});

    	//Regular Expression to test whether the value is valid for time
    	$.tools.validator.fn("[type=time]", "Please supply a valid time", function(input, value) { 
    		return /^\d\d:\d\d$/.test(value);
    	});
    	$.tools.validator.fn("[type=decimal]", "Please supply a valid decimal number", function(input, value) { 
    		return /^[-+]?[0-9]+(\.[0-9]+)?$/.test(value);
    	});
    	$.tools.validator.fn("[type=currency]", "Please supply a valid decimal number", function(input, value) { 
    		return /^\$?[1-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{2})?$/.test(value);
    	});

        $('.library_validate').validator({ 
        	effect: 'wall',
        	container: '#library_form_errors'
        });
        
        
        $(":date").dateinput({

        	// this is displayed to the user
        	format: 'mmm, dd, yyyy',

        	// a different format is sent to the server
        	change: function() {
        		var isoDate = this.getValue('yyyy-mm-dd');

        		$("#backendValue").val(isoDate);
        	}
        });
        
    }

    
	if(typeof $('.library_tinymce').tinymce == 'function'){
        $('.library_tinymce').tinymce({
                // Location of TinyMCE script
                script_url : '/library/jscript/jquery/tiny_mce/tiny_mce.js',

                // General options
                theme : "advanced",
                plugins : "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,advlist",

                // Theme options
                theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
                theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
                theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
                theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
                theme_advanced_toolbar_location : "top",
                theme_advanced_toolbar_align : "left",
                theme_advanced_statusbar_location : "bottom",
                theme_advanced_resizing : true,

                // Example content CSS (should be your site CSS)
                content_css : "css/content.css",

                // Drop lists for link/image/media/template dialogs
                template_external_list_url : "lists/template_list.js",
                external_link_list_url : "lists/link_list.js",
                external_image_list_url : "lists/image_list.js",
                media_external_list_url : "lists/media_list.js",

                // Replace values for the template plugin
                template_replace_values : {
                        username : "Some User",
                        staffid : "991234"
                }
        });
	}
	
	
	$('.library_autoIframeResize').load(function () {
			
		    $(this).height($(this).contents().height() + 50);
		    $(this).width($(this).contents().width());
		});
	
	$('.library_formFileDeleteLink').live('click', function(){
		result = library.util.ajaxSyncCall($(this).attr('href'));
		
		if (result.indexOf('notice') > -1 || result.indexOf('error') > -1){
			
			library.fn.growl(result, true);
		} else {
			$(this).parent().html('');
			library.fn.growl('Succseffully deleted file');
		}
		return false;
	});
		
});
