// NOTE: requires tinymce, jquery, jgrowl and uploadify libs

$(document).ready(function() {
    // NOTE: jQuery Styling
    imageHover('.button');
    $("input").addClass("ui-widget ui-widget-content ui-corner-all");
    $("input:checkbox").removeClass("ui-widget ui-widget-content ui-corner-all");
    $("input:submit").button();
    $("textarea").addClass("ui-widget ui-widget-content ui-corner-all");
    $(".field_name").addClass("ui-state-default").addClass("ui-corner-all");

    $("body").keypress(function(e) {
        if (e.keyCode == '13') {
            return false;
        }
    });
});

function getDataLinks(source, record_id, page) {
    var selector = '#' + page;
    $.ajax({
        type	: "GET",
        url		: "../view/get_" + page + ".php",
        data	: "source=" + source + 
                  "&record_id=" + record_id +
                  "&key=" + key(10000),
        success	: function(html){
            $(selector).empty();
            $(selector).append(html);
        }
    });
}

function setDataLink(source, record_id, link_table, link_id, status) {
    $.ajax({
        type	: "GET",
        url		: "../controller/set_" + link_table + ".php",
        data	: "source=" + source + 
                  "&record_id=" + record_id +
                  "&" + link_table + "_id=" + link_id +
                  "&status=" + status +
                  "&key=" + key(10000),
        success	: function(html){
            var response = html;
            if (response == 1) {
                $.jGrowl('<p></p>' + 'The record has been updated.', {
                    theme	: 'success',
                    header	: 'Record Updated',
                    life	: 4000,
                    sticky	: false
                });
            }
        }
    });
}

function fieldHint(selector) {

    var original_color = $(selector).css('color')
    $(selector).css('color',  '#CCCCCC');

    $(selector).focus(function() {
        if($(this).val() == $(this).attr('defaultValue')) {
            $(this).val('');
            $(this).css('color',  original_color);
        }
    });

    $(selector).blur(function() {
        if($(this).val() == '') {
            $(this).val($(this).attr('defaultValue'));
            $(this).css('color',  '#CCCCCC');
        }
    });
}

// NOTE: This function combines a select menu and a text input field into one "combobox" field.
(function($) {
    $.widget("ui.combobox", {
        _create: function() {
            var self = this;
            var select = this.element.hide();
            var selected = select.val();
            var input = $("<input>")
            .attr({
                name:  "new_" + select.attr("name")
            }).insertAfter(select)
            //.val($('option:selected', select).text())
            .val(selected)
            .autocomplete({
                search: function(e, ui) {
                //alert('SEARCH!');
                //alert($(this).val());
                //alert($(this).attr("name"));
                },
                source: function(request, response) {
                    var matcher = new RegExp(request.term, "i");
                    response(select.children("option").map(function() {
                        var text = $(this).text();
                        if (!request.term || matcher.test(text))
                            return {
                                id: $(this).val(),
                                label: text.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + request.term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
                                value: text
                            };
                    }));
                },
                delay: 0,
                select: function(e, ui) {
                    //alert('SELECT!');
                    if (!ui.item) {
                    // remove invalid value, as it didn't match anything
                    // $(this).val("");
                    // return false;
                    }
                    $(this).focus();
                    select.val(ui.item.id);
                    self._trigger("selected", null, {
                        item: select.find("[value='" + ui.item.id + "']")
                    });

                },
                minLength: 0
            })
            .addClass("ui-widget ui-widget-content ui-corner-left");
            $("<button>&nbsp;</button>")
            .insertAfter(input)
            .button({
                icons: {
                    primary: "ui-icon-triangle-1-s"
                },
                text: false
            }).removeClass("ui-corner-all")
            .addClass("ui-corner-right ui-button-icon")
            .position({
                my: "left center",
                at: "right center",
                of: input,
                offset: "-1 0"
            }).css("top", "")
            .attr({
                title:  "",
                alt:    ""
            }).click(function() {
                // close if already visible
                if (input.autocomplete("widget").is(":visible")) {
                    input.autocomplete("close");
                    return false;
                }
                // pass empty string as value to search for, displaying all results
                input.autocomplete("search", "");
                input.focus();
                return false;
            });
        }
    });

})(jQuery);

function tinymceShow(selector, table, id) {
    $(selector).tinymce({
        script_url : '../scripts/tiny_mce/tiny_mce.js',

        theme : "advanced",
        plugins : "safari,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,spellchecker",

        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect,cleanup,image,code,help,|,fullscreen",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,
		
        //content_css : "../styles/tinymce.css",
        extended_valid_elements : "iframe[src|width|height|name|align|frameborder|scrolling]",
        spellchecker_languages : "+English=en",
        external_image_list_url : "../include/images.php?table=" + table + "&id=" + id,
        external_link_list_url : "../include/links.php?table=" + table + "&id=" + id
    });
}

function tinymceStart(width, height, selector, table, id) {
	
    if (!width) {
        width = "640";
    }
    if (!height) {
        height = "500";
    }

    // Compress
    tinyMCE_GZ.init({
        plugins : "safari,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,spellchecker",
        skin : "o2k7",
        skin_variant : "silver",
        themes : 'advanced',
        languages : 'en',
        disk_cache : true,
        debug : false
    });
	
    // Render
    tinyMCE.init({
        mode : "exact",
        elements : selector,
        skin : "o2k7",
        skin_variant : "silver",
        theme : "advanced",
        plugins : "safari,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,spellchecker",

        relative_urls : false,
        remove_script_host : false,

        width : width,
        height : height,

        theme_advanced_buttons1 : "undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,removeformat,|,tablecontrols",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlremoveformatist,|,outdent,indent,blockquote,|,link,unlink,anchor,|,image,|,hr,charmap,|,sub,sup,|,print,|,spellchecker,|,cleanup,|,help,|,fullscreen,|,code",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        //theme_advanced_resizing : true,
		
        content_css : "../styles/tinymce.css?key=" + key(10000),
        extended_valid_elements : "iframe[src|width|height|name|align|frameborder|scrolling]",
        external_image_list_url : "../include/images.php?table=" + table + "&id=" + id + "&key=" + key(10000),
        external_link_list_url : "../include/links.php?table=" + table + "&id=" + id + "&key=" + key(10000),
        spellchecker_languages : "+English=en",
        spellchecker_rpc_url : "../scripts/tiny_mce_3_2_7/plugins/spellchecker/rpc.php"
    });
}

function imageHover(selector) {
    $(selector).each(function() {
        $(this).hover(function() {
            $(this).stop().animate({
                opacity: 1.0
            }, 50);
        },
        function() {
            $(this).stop().animate({
                opacity: 0.6
            }, 50);
        });
    });
}

function fetchMenu() {
    $.ajax({
        type	: "GET",
        url		: "../table/menu.php",
        data	: "key=" + key(10000),
        success	: function(html){
            $("#menu").empty();
            $("#menu").append(html);
            // Accordion
            $("#menu").accordion({
                header: "h3",
                autoHeight: false,
                animated: false
            });
        }
    });
}

function key(number) {
    return Math.floor(Math.random() * number);
}

function clearUploadQueue() {
    $('#fileUploadgrowl').fileUploadClearQueue();
    $("#upload_controls").hide();
}

function deleteFile(table, id, file_id) {

    $("#delete_file").dialog({
        resizable: false,
        height: 180,
        modal: true,
        buttons: {
            'Delete this file': function() {
                //if (confirm("Delete this file?")) {
                $.ajax({
                    type	: "GET",
                    url		: "../include/delete.php",
                    data	: "table=file" + 
                              "&id=" + file_id +
                              "&key=" + key(10000),
                    success	: function(html){
                        var response = html;
                        if (response == 1) {
                            $.jGrowl('<p></p>' + 'The file has been deleted.', {
                                theme	: 'success',
                                header	: 'File Deleted',
                                life	: 4000,
                                sticky	: false
                            });
                            fetchFiles(table, id);
                        } else {
                            $.jGrowl('<p></p>' + 'The file has not been deleted!', {
                                theme: 	'error',
                                header: 'ERROR',
                                sticky: true
                            });
                        }
                    }
                });
                //}
                $(this).dialog('close');
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        }
    });
}

function deleteRecord(table, id, url) {

    $("#delete_record").dialog({
        resizable: false,
        height: 180,
        modal: true,
        buttons: {
            'Delete this record': function() {
                //if (confirm("Delete this record?")) {
                $.ajax({
                    type	: "GET",
                    url		: "../include/delete.php",
                    data	: "table=" + table + 
                              "&id=" + id +
                              "&key=" + key(10000),
                    success	: function(html){
                        var response = html;
                        if (response == 1) {
                            $.jGrowl('<p></p>' + 'The record has been deleted.', {
                                theme	: 'success',
                                header	: 'Record Deleted',
                                life	: 4000,
                                sticky	: false
                            });
                            window.location = url;
                        } else {
                            $.jGrowl('<p></p>' + 'The record could not been deleted!', {
                                theme: 	'error',
                                header: 'ERROR',
                                sticky: true
                            });
                        }
				
				
                    }
                });
                //}
                $(this).dialog('close');
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        }
    });
}

function enableFile(table, id, file_id) {
    $.ajax({
        type	: "GET",
        url		: "../include/update.php",
        data	: "table=file" +
                  "&id=" + file_id +
                  "&status=enabled" +
                  "&key=" + key(10000),
        success	: function(){
            $.jGrowl('<p></p>' + 'The file status has been updated.', {
                theme	: 'success',
                header	: 'File Enabled',
                life	: 4000,
                sticky	: false
            });
            fetchFiles(table, id);
        }
    });
}

function disableFile(table, id, file_id) {
    $.ajax({
        type	: "GET",
        url		: "../include/update.php",
        data	: "table=file" +
                  "&id=" + file_id +
                  "&status=disabled" +
                  "&key=" + key(10000),
        success	: function(){
            $.jGrowl('<p></p>' + 'The file status has been updated.', {
                theme	: 'success',
                header	: 'File Disabled',
                life	: 4000,
                sticky	: false
            });
            fetchFiles(table, id);
        }
    });
}

function enableRecord(table, id) {
    $.ajax({
        type	: "GET",
        url		: "../include/update.php",
        data	: "table=" + table +
                  "&id=" + id +
                  "&status=enabled" +
                  "&key=" + key(10000),
        success	: function(){
            $.jGrowl('<p></p>' + 'The ' + table + ' status has been updated.', {
                theme	: 'success',
                header	: ucfirst(table) + ' Enabled',
                life	: 4000,
                sticky	: false
            });
            fetchRecords(table);
        }
    });
}

function disableRecord(table, id) {
    $.ajax({
        type	: "GET",
        url		: "../include/update.php",
        data	: "table=" + table +
                  "&id=" + id +
                  "&status=disabled" +
                  "&key=" + key(10000),
        success	: function(){
            $.jGrowl('<p></p>' + 'The ' + table + ' status has been updated.', {
                theme	: 'success',
                header	: ucfirst(table) + ' Disabled',
                life	: 4000,
                sticky	: false
            });
            fetchRecords(table);
        }
    });
}

function updateFileDescription(table, id, file_id) {
    $.ajax({
        type	: "GET",
        url		: "../include/update.php",
        data	: "table=file" +
                  "&id=" + file_id +
                  "&description=" + urlencode($("#file_description_" + file_id).val()) +
                  "&key=" + key(10000),
        success	: function(){
            $.jGrowl('<p></p>' + 'The file description has been updated.', {
                theme	: 'success',
                header	: 'File Description Updated',
                life	: 4000,
                sticky	: false
            });
            fetchFiles(table, id);
        }
    });
}

function fetchFiles(table, id) {
    $.ajax({
        type	: "GET",
        url		: "../include/files.php",
        data	: "source=" + table + 
                  "&record_id=" + id +
                  "&key=" + key(10000),
        success	: function(html){
            $("#files").empty();
            $("#files").append(html);
			
            makeSortable('file');
            showFileTypes();

            imageHover('.button');
            $("input").addClass("ui-widget ui-widget-content ui-corner-all");
            $("input:checkbox").removeClass("ui-widget ui-widget-content ui-corner-all");
            $("input:submit").button();
            $("textarea").addClass("ui-widget ui-widget-content ui-corner-all");
        }
    });
}

function fetchRecords(table) {
    $.ajax({
        type	: "GET",
        url		: "../include/records.php",
        data	: "table=" + table +
                  "&key=" + key(10000),
        success	: function(html){
            $("#records").empty();
            $("#records").append(html);
			
            makeSortable(table);
            
            imageHover('.button');
            $("input").addClass("ui-widget ui-widget-content ui-corner-all");
            $("input:checkbox").removeClass("ui-widget ui-widget-content ui-corner-all");
            $("input:submit").button();
            $("textarea").addClass("ui-widget ui-widget-content ui-corner-all");
        }
    });
}

function fetchBackup(table) {
    $.ajax({
        type	: "GET",
        url		: "../include/backup.php",
        data	: "table=" + table + "&key=" + key(10000),
        success	: function(html){
            $("#backup").empty();
            $("#backup").append(html);

            imageHover('.button');
        }
    });
}

function makeSortable(table) {
    
    $("#sortable").sortable({
        handle : '.handle',
        placeholder : 'ui-state-highlight', 
        update : function () {
            var order = $('#sortable').sortable('serialize');
            $.ajax({
                type	: "POST",
                url		: "../include/sortable.php",
                data	: "table=" + table +
                          "&key=" + key(10000) +
                          "&" + order,
                success	: function(){
                    $.jGrowl('<p></p>' + 'The ' + table + ' sequence has been updated.', {
                        theme	: 'success',
                        header	: 'Sequence Updated',
                        life	: 4000,
                        sticky	: false
                    });
                }
            });
        }
    });

    $("#sortable li")
    .hover(
        function() {
            $(this).addClass("ui-state-hover");
        },
        function(){
            $(this).removeClass("ui-state-hover");
        })
    .addClass("ui-corner-all");
    
    $("#sortable").disableSelection();
}

function imagePreview(selector) {
    if ($(selector).length > 0 ) {
        $(selector).imgPreview({
            //imgCSS: { width: 200 },
            srcAttr: 'rel'
        });
    }
}

function showFileTypes() {
    $(".pdf").addClass("pdf");
    $(".doc").addClass("word");
    $(".docx").addClass("word");
    $(".xls").addClass("excel");
    $(".xlsx").addClass("excel");
    $(".ppt").addClass("powerpoint");
    $(".gz").addClass("compressed");
    $(".zip").addClass("compressed");
    $(".txt").addClass("text");
    $(".swf").addClass("flashy");
	
    $(".jpeg").addClass("image");
    imagePreview(".jpeg");
    $(".jpg").addClass("image");
    imagePreview(".jpg");
    $(".gif").addClass("image");
    imagePreview(".gif");
    $(".png").addClass("image");
    imagePreview(".png");
}

function loadUploader(selector, table, id, fileDIR, file_types, file_size, protect) {
	
    if (typeof(protect) == 'undefined') {
        protect = 0;
    }
	
    $(selector).fileUpload({
        'uploader'		: '../uploadify/uploadify/uploader.swf',
        'cancelImg'		: '../uploadify/uploadify/cancel.png',
        'script'		: '../uploadify/uploadify/upload.php',
        //'checkScript'	: '../uploadify/uploadify/check.php', // has bugs in internet explorer
        'folder'		: '../../' + fileDIR,
        'buttonText'	: 'Select Files',
        'fileDesc'	    : 'Files',
        'fileExt'		: file_types,
        'multi'			: true,
        'simUploadLimit': 3,
        'sizeLimit'		: file_size,
        onSelect: function (event, queueID ,fileObj) {
			
            $.ajax({
                type	: "GET",
                url		: "../include/check.php",
                data	: "name=" + urlencode(fileObj.name) +
                          "&key=" + key(10000),
                success	: function(html){
                    var response = html;
                    // CHECK AND REPLACE
                    // OR
                    // CHECK AND CANCEL
                    if (response == 1) {
                        $.jGrowl('<p></p>' + 'The file "' + fileObj.name + '" already exists!', {
                            theme: 	'error',
                            header: 'ERROR',
                            sticky: true
                        });
                        $(selector).fileUploadCancel(queueID);
                    }
                }
            });
        },
        onSelectOnce: function () {
            $("#upload_controls").show();
        },
        onError: function (event, queueID ,fileObj, errorObj) {
            var msg;
            if (errorObj.status == 404) {
                msg = 'Could not find upload script.';
            } else if (errorObj.type === "HTTP")
                msg = errorObj.type + ": " + errorObj.status;
            else if (errorObj.type === "File Size")
                msg = fileObj.name + ' is too big! <br/>' + errorObj.type + ' Limit: ' + Math.round(errorObj.sizeLimit / 1024 / 1024) + 'MB';
            else
                msg = errorObj.type + ": " + errorObj.text;
            $.jGrowl('<p></p>' + msg, {
                theme: 	'error',
                header: 'ERROR',
                sticky: true
            });
            $(selector + queueID).fadeOut(250, function() {
                $(selector + queueID).remove()
            });
            $("#upload_controls").hide();
            return false;
        },
        onCancel: function (event, queueID, fileObj, data) {
            var msg = "Cancelled uploading: " + fileObj.name;
            $.jGrowl('<p></p>' + msg, {
                theme: 	'warning',
                header: 'Cancelled Upload',
                life:	4000,
                sticky: false
            });
            if (data.fileCount == 0) {
                $("#upload_controls").hide();
            }
        },
        onClearQueue: function (event, data) {
            var msg = "Cleared " + data.fileCount + " files from queue.";
            $.jGrowl('<p></p>' + msg, {
                theme: 	'warning',
                header: 'Cleared Queue',
                life:	4000,
                sticky: false
            });
        },
        onComplete: function (event, queueID ,fileObj) {
            $.ajax({
                type	: "GET",
                url		: "../include/file.php",
                data	: "insert=1&protect=" + protect +
                          "&record_id=" + id +
                          "&source=" + table +
                          "&name=" + urlencode(fileObj.name) +
                          "&size=" + fileObj.size +
                          "&key=" + key(10000),
                success	: function(){
                    var size = Math.round(fileObj.size / 1024);
                    $.jGrowl('<p></p>' + fileObj.name + ' - ' + size + 'KB', {
                        theme	: 'success',
                        header	: 'Upload Complete',
                        life	: 4000,
                        sticky	: false
                    });
                    fetchFiles(table, id);
                }
            });
        },
        onAllComplete: function (event, data) {
            $("#upload_controls").hide();
        }/*,
		onSelectOnce: function (event, data) {
			$("#queue_size").append(Math.round(data.allBytesTotal / 1024) + 'KB');
		}*/
    });
}

function uploader(options) {
    if (typeof(options.protect) == 'undefined') {
        options.protect = 0;
    }
    var uploader = new qq.FileUploader({
        // pass the dom node (ex. $(selector)[0] for jQuery users)
        element: document.getElementById('file-uploader'),
        // path to server-side upload script
        action: '/application/controller/upload.php',
        // validation
        // ex. ['jpg', 'jpeg', 'png', 'gif'] or []
        buttonText: 'Select Files',
        allowedExtensions: options.file_types,
        // each file size limit in bytes
        // this option isn't supported in all browsers
        sizeLimit: options.file_size,  // max size
        onComplete: function(id, fileName, responseJSON) {
            //alert(responseJSON.fileName + ' : ' + responseJSON.success);
            $.ajax({
                type: 'GET',
                url: '/control/include/file.php',
                data: {
                    insert: 1,
                    protect: options.protect,
                    record_id: options.id,
                    source: options.table,
                    name: urlencode(responseJSON.fileName),
                    size: responseJSON.fileSize,
                    key: key(10000)
                },
                success: function () {
                    $.jGrowl('<p></p>' + responseJSON.fileName + ' - ' + Math.round(responseJSON.fileSize / 1024) + 'KB', {
                        theme: 'success',
                        header: 'Upload Complete',
                        life: 4000,
                        sticky: false
                    });
                    fetchFiles(options.table, options.id);
                }
            });
        },
        onCancel: function(id, fileName) {
            $.jGrowl('<p></p>' + 'Cancelled uploading: ' + fileName, {
                theme: 'warning',
                header: 'Cancelled Upload',
                life: 4000,
                sticky: false
            });
        }
    });
}