﻿/// <reference path="jquery-1.3.2-vsdoc.js" />

jQuery.fn.exists = function() { return jQuery(this).length > 0; }

//extraído de http://jonraasch.com/blog/a-simple-jquery-slideshow
function slideSwitch() {
    var $active = $('.slideshow IMG.active');
    if ($active.length == 0) $active = $('.slideshow IMG:last');

    // use this to pull the images in the order they appear in the markup        
    var $next = $active.next().length ? $active.next() : $('.slideshow IMG:first');

    $active.addClass('last-active');
    $next.css({ opacity: 0.0 })
                    .addClass('active')
                    .animate({ opacity: 1.0 }, 1000, function() {
                        $active.removeClass('active last-active');
                    });
}

function iniciarSlideShowAutomatico(delay) {
    setInterval('slideSwitch()', delay);
}

jQuery.fn.slideShow = function(delay) {
    document.currentImage = 1;
    var image = this;

    setInterval(function() {
        if (document.currentImage == images.length) {
            document.currentImage = 0;
        }
        $(image).css({ opacity: 0.3 })
                    .attr('src', images[document.currentImage])
                    .animate({ opacity: 1.0 }, 2000);
        document.currentImage = document.currentImage + 1;                
    }, delay);
    return jQuery(this);
}

function openPopUp(link, height, width) {
    // Place the window
    var top = (screen.width - width) / 2;
    var left = (screen.height - height) / 2;

    //Get what is below onto one line
    w = window.open(link, 'SomePopUp' + new Date().getTime(),
                          'height=' + height + 'width=' + width + ',top=' + top + ',left=' + left +
                          ',fullscreen=no,toolbar=no,location=no,directories=no,status=no,titlebar=no,\
                           menubar=no,scrollbars=no,resizable=yes');
    return w;
}

function selectElement(selector) {
    $(selector).addClass('selected');
}

// extraído de http://www.devx.com/webdev/Article/20947
function MM_preloadImages() {
    var d = document;

    if (d.images) {
        if (!d.MM_p)
            d.MM_p = new Array();

        var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
        for (i = 0; i < a.length; i++) {
            if (a[i].indexOf("#") != 0) {
                d.MM_p[j] = new Image;
                d.MM_p[j++].src = a[i];
            }
        }
    }
}

/*
// otro enfoque para cachear imagenes
// extraído de http://www.dannyg.com/javascript/imgobj/imgobject.htm
imageDB = new Array(4)
for (var i = 0; i < imageDB.length; i++) {
imageDB[i] = new Image(120, 90)
imageDB[i].src = "desk" + (i + 1) + ".gif"
}
*/

function inicializarLoginControl(containerwidth) {
    $('#a2').css('padding', '2px').corner("round 4px").parent().css('padding', '1px').corner("round 6px");
    $('#b2').corner("round 4px").parent().css('padding', '1px').corner("round 6px");
    $('input[type!=submit]')
            .focus(function() { $(this).addClass('selected'); })
            .blur(function() { $(this).removeClass('selected'); });
    if (containerwidth != undefined)
        $('#a1').css('width', containerwidth);
    $('.login input[type!=submit]:first').focus();
}

function inicializarForm() {
    $('.frm input[type!=submit]:not(:disabled,.fecha), .frm textarea:not(:disabled)')
            .focus(function() { $(this).addClass('selected'); })
            .blur(function() { $(this).removeClass('selected'); });
    var txt = $('.frm input[type!=submit]:not(:hidden, :disabled, .fecha):first');
    if (txt.exists())
        txt.focus();
    else
        $('.frm textarea:first').focus();
}

function confirmDelete(s) {
    return confirm(s);
}

function getProportion(height, width, element, maxheight, maxwidth) {
    var proportion = 0;
    if (width > maxwidth && height > maxheight) {
        proportion = (width > height) ? (maxwidth / width) : (maxheight / height);
    } else if (width > maxwidth) {
        proportion = maxwidth / width;
    } else if (height > maxheight) {
        proportion = maxheight / height;
    }
    return proportion;
}


jQuery.fn.resize = function(maxheight, maxwidth) {
    for (i = 0; i < jQuery(this).length; i++) {
        var $element = jQuery(this)[i];
        var height = jQuery($element).height();
        var width = jQuery($element).width();
        var proportion = getProportion(height, width, maxheight, maxwidth);
        if (proportion > 0) {
            jQuery($element).width(width * proportion).height(height * proportion);
        }
    }
    return jQuery(this);
}

jQuery.fn.resizeImages = function(maxheight, maxwidth) {
    for (i = 0; i < jQuery(this).length; i++) {
        var $imagen = jQuery($(this)[i]);
        var img = new Image();
        img.src = $imagen.attr('src');
        var $imgresized = $(img);
        var proportion = getProportion(img.height, img.width, maxheight, maxwidth);
        if (proportion > 0) {
            $imagen.width(img.width * proportion).height(img.height * proportion);
        }
    }
}

var SlideShow = (function() {
    var privateCounter = 0;

    function goToImageNumber(val) {
        if (val < 0)
            privateCounter = images.length - 1;
        else
            privateCounter = val % images.length;
        $('img#imgslider').attr('src', images[privateCounter]);
        $('span#posicion').text((privateCounter + 1) + ' de ' + images.length);
        var maxh = $('#images #imgcontainer').height(), maxw = $('#images #imgcontainer').width();
        $('#images #imgcontainer img').resize(maxh, maxw);
    }

    function prev(e) {
        e.preventDefault();
        goToImageNumber(privateCounter - 1);
    }

    function next(e) {
        e.preventDefault();
        goToImageNumber(privateCounter + 1);
    }

    return {
        first: function() {
            if (typeof (images) == "undefined")
                return;
            var maxHeight = 0, maxWidth = 0;
            for (i = 0; i < images.length; i++) {
                var img = new Image();
                img.src = images[i];
                if (img.height > maxHeight) {
                    maxHeight = img.height;
                }
                if (img.width > maxWidth) {
                    maxWidth = img.width;
                }
            }
            var proportion = (maxWidth > 370) ? (370 / maxWidth) : 1;
            $('#images #imgcontainer img').ready(function() { $(this).width(maxHeight * proportion); });
            $('.botonesnavegacion .btnprev').click(prev);
            $('.botonesnavegacion .btnnext').click(next);
            goToImageNumber(0);
        },
        last: function() {
            goToImageNumber(images.length);
        },
        value: function() {
            return privateCounter;
        }
    }
})();

function showResult(element, color) {

    var position = $(element).offset();
    var attr = {
        'top': position.top,
        'left': position.left,
        'position': 'absolute',
        'z-index': 100,
        'background-color': color,
        'width': $(element).width() + 5,
        'height': $(element).height() + 5,
        'opacity': 0.65
    };
    var $div = $(element).before('<div></div>');
    $(element).prev('div').css(attr).fadeTo(2000, 0, function() { $(this).remove(); });
}

//inline grid
function inlineGrid(updateData, getDataToPost, getDeleteMessage, isCreate, inicializarControles) {
    function mostrarResultados(j, btn) {
        $('.results').load(pathResults);
        if (j.result) {
            disableControls(btn, false);
        }
    }

    function saveData(btn) {
        var data = getDataToPost(btn);
        $.post(data.url, data, function(j) { mostrarResultados(j, btn); }, 'json');
    }

    function onDelete(j, btn) {
        if (j.result) {
            $(btn).closest('tr').replaceWith('');
            $('.results').load(pathResults);
        }
    }

    function deleteData(btn) {
        var elimina = confirm(getDeleteMessage(btn));
        if (elimina) {
            $.post($(btn).attr('href'), {}, function(j) { onDelete(j, btn); }, 'json');
        }
    }

    function enableControls(btn) {
        var $next = $(btn).closest('td').nextAll();
        $(btn).closest('td').children('div').toggle();
        $next.children(':disabled').attr('disabled', '');
        var spans = $next.children('span');
        for (i = 0; i < spans.length; i++) {
            var item = spans[i];
            var html = '<input type="text" value="{0}" name="{1}"></input>';
            html = html.replace('{0}', $(item).text());
            html = html.replace('{1}', $(item).attr('name'));
            $(item).replaceWith(html);
        };
    }

    function disableAllControls(btn) {
        var $next = $(btn).closest('td').nextAll();
        $(btn).closest('td').children('div').toggle();
        $next.children(':enabled').attr('disabled', 'disabled');
        var spans = $next.children(':text');
        for (i = 0; i < spans.length; i++) {
            var item = spans[i];
            var html = '<span name="{0}">{1}</span>';
            html = html.replace('{0}', $(item).attr('name'));
            html = html.replace('{1}', $(item).val());
            $(item).replaceWith(html);
        };
    }

    function disableControls(btn, hideResults) {
        if (isCreate(btn) || !hideResults) {
            disableAllControls(btn);
            $.get(pathGridData, {}, function(data) {
                $('.griddata').html(data);
                $('td.actions div.editing').toggle();
            }, 'html');            
        } else {
            if (hideResults) {
                $(".results").animate({ opacity: 0 }, 500, "linear",
                            function() {
                                $('.results').html('');
                                $('.results').css('opacity', '1');
                                $(btn).closest('tr').remove();
                            });
            }
        }
    }

    function onClickAction(e) {
        e.preventDefault();
        if ($(this).hasClass('edit')) {
            enableControls(this);
        } else if ($(this).hasClass('cancel')) {
            disableControls(this, false);
        } else if ($(this).hasClass('save')) {
            saveData(this);
        } else if ($(this).hasClass('delete')) {
            deleteData(this);
        }
    }

    function onClickCreate(e) {       
        e.preventDefault();
        var row = $('.griddata tbody tr:last').html();
        $('.gridview tbody').append('<tr></tr>');
        $('.gridview tbody tr:last').html(row);
        $('.gridview tr:last :input:hidden').val(0);
        var cssclass = 'gridrow';
        if (($('.griddata tr').size() % 2) == 1) {
            cssclass = 'gridaltrow';
        }
        $('.gridview tr:last').addClass(cssclass);
        enableControls($('.gridview tr:last .edit'));
        inicializarControles();
    }

    $('a.create').click(onClickCreate);
    $.get(pathGridData, {}, function(data) {
        $('.griddata').html(data);
        $('td.actions div.editing').toggle();
        $('td.actions a.t').live('click', onClickAction);
    }, 'html');
}

//TextArea Resizer
//http://plugins.jquery.com/project/TextAreaResizer
(function($) {
    var textarea, staticOffset;
    var iLastMousePos = 0;
    var iMin = 32;
    var grip;

    $.fn.TextAreaResizer = function() {
        return this.each(function() {
            textarea = $(this).addClass('processed'), staticOffset = null;
            $(this).wrap('<div class="resizable-textarea"><span></span></div>')
		      .parent().append($('<div class="grippie"></div>').bind("mousedown", { el: this }, startDrag));

            var grippie = $('div.grippie', $(this).parent())[0];
            grippie.style.marginRight = (grippie.offsetWidth - $(this)[0].offsetWidth) + 'px';

        });
    };

    /* private functions */
    function startDrag(e) {
        textarea = $(e.data.el);
        textarea.blur();
        iLastMousePos = mousePosition(e).y;
        staticOffset = textarea.height() - iLastMousePos;
        //textarea.css('opacity', 0.25);
        $(document).mousemove(performDrag).mouseup(endDrag);
        return false;
    }

    function performDrag(e) {
        var iThisMousePos = mousePosition(e).y;
        var iMousePos = staticOffset + iThisMousePos;
        if (iLastMousePos >= (iThisMousePos)) {
            iMousePos -= 5;
        }
        iLastMousePos = iThisMousePos;
        iMousePos = Math.max(iMin, iMousePos);
        textarea.height(iMousePos + 'px');
        if (iMousePos < iMin) {
            endDrag(e);
        }
        return false;
    }

    function endDrag(e) {
        $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag);
        //textarea.css('opacity', 1);
        textarea.focus();
        textarea = null;
        staticOffset = null;
        iLastMousePos = 0;
    }

    function mousePosition(e) {
        return { x: e.clientX + document.documentElement.scrollLeft, y: e.clientY + document.documentElement.scrollTop };
    };
})(jQuery);

jQuery.fn.hideMessage = function() {
    var id;
    var $element = jQuery(this);
    id = setInterval(
        function() {
            jQuery($element).animate({ opacity: 0.0 }, 1500, 'linear', function() { jQuery($element).hide(); });
            clearInterval(id);
        },
        1000 * 5);
}
