﻿/*Uses JQUERY*/
//Method to check if object exists
jQuery.exists = function(obj) { return ($(obj).length > 0); }


$(document).ready(function() {
    //Load on Asychronous Post Back (Applies to Update Panel) 
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    function EndRequestHandler(sender, args) {
        if (args.get_error() == undefined) {

            hideNewItem();
            toggleNewItem();

            datePicker();

            dateTimePicker();

            timePicker();

            loadTinyMCE();

            loadUpdatePanelEffects();

            centerObj();

            picPreview();

            copyClipboard();        

            //loadDialog();

            //loadAccordion();          
        }
    }

    //Otherwise Load
    hideNewItem();
    toggleNewItem();

    datePicker();

    dateTimePicker();

    timePicker();

    firstPageLoadEffects();

    loadTinyMCE();

    MenuMethods();

    centerObj();

    picPreview();

    copyClipboard();

    //loadDialog();

    //loadAccordion();

});

function loadDialog() {  

    //Initialise Dialog
    $('#Dialog').dialog({
        autoOpen: false,
        title: '',
        show: 'fade',
        hide: 'fade',
        width:'500px',
	    modal: true
    });

    //Open Dialog
    $('#OpenDialog').click(function() {    
    $.fx.speeds._default = 1000;
    $('#Dialog').dialog('open');
        return false;
    });
}

function loadAccordion() {
    jQuery('#Accordion').accordion({
        collapsible: true,
        autoHeight: true
    });
}

   function datePicker() {
    $(".DatePicker").datepicker(
            { dateFormat: 'dd/mm/yy',
              showOtherMonths: true,
              showOn: 'focus',
            showStatus: true,
              showButtonPanel: true,
              numberOfMonths: 3              
            });

        }


        function dateTimePicker() {
            $(".DateTimePicker").datetimepicker(
                { dateFormat: 'dd/mm/yy',
                    showOn: 'focus',
                    showStatus: true,
                    showButtonPanel: true,
                    hourMin: 9,
                    hourMax: 17

                });
        }    

        function timePicker() {
            $(".TimePicker").timepicker(
                {   
            });
        }    

        function firstPageLoadEffects() {
            //Jquery Effects
            $(".SearchTable").show("bounce", {times: 3}, 300);
            $(".SubMenu").show("fold", {}, 1000);           
        }

        function loadUpdatePanelEffects() {
            //Jquery Effects           
            $(".ModalMenu").show("highlight", {}, 2000);
        }
        
        function toggleNewItem(){
        
             $('.ToggleNewItem').click(function() {
             $('.NewItem').toggle(400);
            });
        }

        //Create JQUERY Function which is used to center updateProgress
        jQuery.fn.center =
        function() {
                this.css("position", "absolute");
                this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
                this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
                return this;
            }

            function centerObj() {
                $('.autoCenter').center(); 
            }                 
 
      
      function loadTinyMCE() {
          tinyMCE.init({
            // General options
            mode: "textareas",
            editor_selector: "TinyMCETextEditor",
            theme: "advanced",
            plugins: "safari,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,imagemanager,filemanager",
            skin: "o2k7",
            skin_variant: "silver",
            //Extend valid HTML Elements to allow iFrames.
            extended_valid_elements: "iframe[src|width|height|name|align]",
           
            // Theme options
            theme_advanced_buttons1: "save,newdocument,|,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,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage", 
            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/example.css",

            // Drop lists for link/image/media/template dialogs
           // template_external_list_url: "js/template_list.js",
            //external_link_list_url: "../Javascript/tiny_mce/LinkList.js",
            //external_image_list_url: "../Javascript/tiny_mce/ImageList.js",


            //media_external_list_url: "js/media_list.js",
            
            // Replace values for the template plugin
            template_replace_values: {
                username: "Some User",
                staffid: "991234"
            },
            
            setup: function(ed) {
                    //Save Contents on Change
                    ed.onChange.add(function(ed) { saveTinyMCEContent(); });
             }     
                               
        });
        
    }

    //Client validation to check if TinyMCEField is empty
    function chkTinyMCEField(sender, args) {
        args.IsValid = false;
        $(".TinyMCETextEditor").each(function() {
        var re = /^[ \t]+|[ \t]+$/ //Match any white space including space, tab, form-feed, etc. 
        RegExp.multiline = true; // IE support
        var str = this.value.replace(re, "");       
        if ((str.length > 0))
            {
                args.IsValid = true;
            }
        });
    }

    //Method Saves TinyMCE Editor Back to Text Area
    function saveTinyMCEContent() {
        tinyMCE.triggerSave();
    }
    
   function hideNewItem() {
        $('.NewItem').hide();
    }

    function MenuMethods() {
    
             $('#nav li').hover(   
                function () {   
                   //show its submenu   
                    $('ul', this).slideDown(200);  
               },    
                function () {   
                    //hide its submenu
                    $('ul', this).slideUp(200);            
                }   
            );

            }

         //IMGPreview Method
            jQuery.fn.imagePreview = function() {
                /* CONFIG */
                
                xOffset = 10;
                yOffset = 30;
                // these 2 variable determine popup's distance from the cursor
                // you might want to adjust to get the right result

                /* END CONFIG */
                $("a.preview").hover(function(e) {
                    this.t = this.title;
                    this.title = "";
                    var c = (this.t != "") ? "<br/>" + this.t : "";
                    $("body").append("<p id='preview'><img src='" + this.href + "' alt='Image preview' />" + c + "</p>");
                    $("#preview")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px")
			.fadeIn("fast");
                },
	            function() {
	                this.title = this.t;
	                $("#preview").remove();
	            });
                            $("a.preview").mousemove(function(e) {
                                $("#preview")
			            .css("top", (e.pageY - xOffset) + "px")
			            .css("left", (e.pageX + yOffset) + "px");
                            });
            };

            function picPreview() {
                $('.preview').imagePreview();
            }


            //ZeroClipboard method
            function copyClipboard() {
                $(function() {
                $(".gridCopyClipboard tbody tr:odd").addClass("altrow");
                $(".gridCopyClipboard tbody tr:even").addClass("row");

                $(".gridCopyClipboard tbody td:last-child").each(function() {
                        //Create a new clipboard client
                        var clip = new ZeroClipboard.Client();

                        //Cache the last td and the parent row    
                        var lastTd = $(this);
                        var parentRow = lastTd.parent("tr");

                        //Glue the clipboard client to the last td in each row
                        clip.glue(lastTd[0]);

                        //Grab the text from the parent row of the icon
                        var txt = $.trim($("td:first-child", parentRow).text());
                        clip.setText(txt);

                        //Add a complete event to let the user know the text was copied
                        clip.addEventListener('complete', function(client, text) {
                        alert("Copied text to clipboard:\n" + text);
                        });
                    });
                });
            }                                   

    //JS Function used on the Tab AjaxToolKitControl for the RFW Detail to carry out
    //postback to refresh modal panel position. Just add function to the tab property OnClientActiveTabChanged
    function ActiveTabChanged(sender, e) {
        doPostBackAsync('EventName', 'EventArgs');
    }

    function doPostBackAsync(eventName, eventArgs) 
    {
        var prm = Sys.WebForms.PageRequestManager.getInstance();

        if (!Array.contains(prm._asyncPostBackControlIDs, eventName)) {
            prm._asyncPostBackControlIDs.push(eventName);
        }

        if (!Array.contains(prm._asyncPostBackControlClientIDs, eventName)) {
            prm._asyncPostBackControlClientIDs.push(eventName);
        }

        __doPostBack(eventName, eventArgs);
    }

