
Vri = {

    version: '1.0',

    redirect: function(url, target) {
        var anchor_pos = url.indexOf("#");
        if (null == target) {
            target = document;
        }
        target.location.href = (anchor_pos == -1) ? url : url.substr(0, anchor_pos);
    },

    hrefMsgPrep: function(msg_type, msg) {
        return Vri.hrefReplace({'msg_type': msg_type, 'msg': msg});
    },

    hrefReplace: function(replacements) {
        var reg;
        var data;
        var new_idx;
        var current_search = document.location.search;
        for(var idx in replacements)
        {
            data = replacements[idx];
            if(current_search.indexOf(idx+'=') == -1)
            {
                //console.log('Append ' + idx + ' ' + current_search);
                current_search += ((current_search)?'&':'?') + idx + '=' + escape(data);
            }
            else
            {
                //console.log('Replaced ' + idx + ' ' + current_search);
                new_idx = idx.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1");
                reg = new RegExp('(\\&|\\?)('+new_idx+')=[^\\&]+' , 'i');
                current_search = current_search.replace(reg, '\$1' + idx + '=' + escape(data));
            }

        }
        current_search = current_search.replace(/^\&/,'?');
        return document.location.protocol + '//' + document.location.host + document.location.pathname + current_search;
    },

    reload: function(target) {
      if (null == target) {
          target = document;
      }
      Vri.redirect(target.location.href);
    },

    showSuccessMessage: function(msg, title) {
        if($.pnotify) {
            if (!title) {
                title = 'Request successfull';
            }
            $.pnotify({
                pnotify_title: title,
                pnotify_text: msg || 'Success',
                pnotify_type: 'success'
            });
        } else {
            alert(msg);
        }
    },

    showErrorMessage: function(msg) {
        if($.pnotify) {
            $.pnotify({
                pnotify_title: 'An error occured',
                pnotify_text: msg || 'Unknown error occurred',
                pnotify_type: 'error'
            });
        } else {
            alert(msg);
        }
    }

};


Vri.Paginator = function(form, checkboxAll) {
    this.form = document.getElementById(form);
    this.checkboxAll = document.getElementById(checkboxAll);
};


Vri.Paginator.prototype = {

    form: null,
    checkboxAll: null,

    clearCheckboxes: function(el) {
        if (el.checked == false && this.checkboxAll && this.checkboxAll.checked == true) {
            this.checkboxAll.checked = false;
        }
    },

    mousedown: function(el) {
        if (el.disabled == false) {
            el.checked = !el.checked;
        }
    },

    selectCheckboxes: function(el, name) {
        for(var i=0; i<el.form.length; ++i) {
            if (el.form[i].type != 'checkbox') {
                continue;
            }

            if (el.form[i] == el && el.form[i]) {
                continue;
            }

            if (el.form[i] == this.checkboxAll) {
                continue;
            }

            if (name && el.form[i].name != name+'[]') {
                continue;
            }

            el.form[i].checked = el.checked ? true : false;
        }
    },

    getSelected: function() {
        var selected = [];
        for(var count=0, i=0; i<this.form.length; i++) {
            if (this.form[i].type == 'checkbox' && this.form[i] != this.checkboxAll && this.form[i].checked == true) {
                selected.push(this.form[i].value);
            }
        }
        return selected;
    },

    countSelected: function() {
        for(var count=0, i=0; i<this.form.length; i++) {
            if (this.form[i].type == 'checkbox' && this.form[i] != this.checkboxAll && this.form[i].checked == true) {
                ++count;
            }
        }
        return count;
    },

    confirmBulkAction: function(msg, type, url, standard_submit) {
        var count = this.countSelected();
        if (count < 1) {
            return false;
        }

        var cMsg = msg + ' ' + count + ' ' + type + '?';

        if (!confirm(cMsg)) {
            return false;
        }

        if (standard_submit == true) {
            this.form.action = url;
            this.form.submit();
            return false;
        }

        var form = this.form;

        try {
            var data = $(this.form).formToArray();
        } catch(err) {
            if($.pnotify)
            {
                $.pnotify({
                    pnotify_title: 'An error occured',
                    pnotify_text: err,
                    pnotify_type: 'error'
                });
            }
            else
                alert(err);
        }

        var test = 1;

        $.ajax({
           type: 'POST',
           url: url,
           cache: false,
           data: data,
           dataType: 'json',
           success: function(data, textStatus, request){
                if (data && data.success == true) {
                    var current_href = Vri.hrefMsgPrep('success', 'Successfully updated');
                    setTimeout(function() { Vri.redirect(current_href);}, 200);
                } else {
                    var msg = (data && data.message) ? data.message : 'Unknown error';
                    if($.pnotify)
                    {
                        $.pnotify({
                            pnotify_title: 'An error occured',
                            pnotify_text: msg,
                            pnotify_type: 'error'
                        });
                    }
                    else
                        alert(msg);
                }
           },
           error: function(data, textStatus, request) {
                var msg = (data && data.message) ? data.message : 'Unknown error';
                if($.pnotify)
                {
                    $.pnotify({
                        pnotify_title: 'An error occured',
                        pnotify_text: msg,
                        pnotify_type: 'error'
                    });
                }
                else
                    alert(msg);
           }
         });

        return false;
    },

    confirmSingleAction: function(msg, type, url, standard_submit) {
        var cMsg = msg + ' ' + type + '?';

        if (!confirm(cMsg)) {
            return false;
        } else {
            return this.singleAction(msg, type, url, standard_submit);
        }
    },

    singleAction: function(msg, type, url, standard_submit) {
        if (standard_submit == true) {
            this.form.action = url;
            this.form.submit();
            return false;
        }

        try {
            //var data = $(this.form).formToArray();
            var data = new Array();
        } catch(err) {
            if($.pnotify)
            {
                $.pnotify({
                    pnotify_title: 'An error occured',
                    pnotify_text: err,
                    pnotify_type: 'error'
                });
            }
            else
                alert(err);
        }

        //alert(url);
        $.ajax({
           type: 'POST',
           url: url,
           cache: false,
           data: data,
           dataType: 'json',
           success: function(data, textStatus, request){
                if (data && data.success == true) {
                    if (data.message != '') {
                        $.pnotify({
                            pnotify_title: 'Success',
                            pnotify_text: data.message,
                            pnotify_type: 'success'
                        });
                    }
                    //Strip out any previous messages
                    var current_href = Vri.hrefMsgPrep('success', 'Successfully updated');

                    setTimeout(function() { Vri.redirect(current_href);}, 200);

                } else {
                    var msg = (data && data.message) ? data.message : 'Unknown error';
                    if($.pnotify)
                    {
                        $.pnotify({
                            pnotify_title: 'An error occured',
                            pnotify_text: msg,
                            pnotify_type: 'error'
                        });
                    }
                    else
                        alert(msg);
                }
           },
           error: function(data, textStatus, request) {
                var msg = (data && data.message) ? data.message : 'Unknown error';
                if($.pnotify)
                {
                    $.pnotify({
                        pnotify_title: 'An error occured',
                        pnotify_text: msg,
                        pnotify_type: 'error'
                    });
                }
                else
                    alert(msg);
           }
         });

        return false;
    }

};//Vri.Paginator

/**
 * YOU ARE FREE TO USE THIS CODE IF YOU HOLD THE REFERENCE TO THE AUTHOR
 * Plugin for jQuery that delimites the maximum of characteres in inputs and textareas
 * @author: Iv�n Guardado Castro
 * @email: dev.ivangc@gmail.com
 * @website: http://yensdesign.com/
 */
jQuery.fn.maxLength = function(max){
	this.each(function(){
		//Get the type of the matched element
		var type = this.tagName.toLowerCase();
		//If the type property exists, save it in lower case
		var inputType = this.type? this.type.toLowerCase() : null;
		//Check if is a input type=text OR type=password
		if(type == "input" && inputType == "text" || inputType == "password"){
			//Apply the standard maxLength
			this.maxLength = max;
		}
		//Check if the element is a textarea
		else if(type == "textarea"){
			//Add the key press event
			this.onkeypress = function(e){
				//Get the event object (for IE)
				var ob = e || event;
				//Get the code of key pressed
				var keyCode = ob.keyCode;
				//Check if it has a selected text
				var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
				//return false if can't write more
				return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
			};
			//Add the key up event
			this.onkeyup = function(){
				//If the keypress fail and allow write more text that required, this event will remove it
				if(this.value.length > max){
					this.value = this.value.substring(0,max);
				}
			};
		}
	});
};

jQuery.fn.tabify = function() {
    this.each(function() {
        $(this).addClass('ui-tabs ui-widget ui-widget-content ui-corner-all')
            .find('ul:first')
                .addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all')
                .find('li')
                    .addClass('ui-state-default ui-corner-top')
                    .hover(function() {$(this).addClass('ui-state-hover')}, function() {$(this).removeClass('ui-state-hover')})
                .end()
            .end()
            .children('div[id^=tabs-]')
                .addClass('ui-tabs-panel ui-widget-content ui-corner-bottom');
    });
}

$(document).ready(function() {
    $('.corner').corner("5px keep");
    $('.corner_top').corner("top");
    $("button, input:submit, input:reset, a", ".prettify").button();
});

function suClick(item, $source)
{
    $('#lookahead_member_id').val( $(item).data('item_data')['id'] );
    //$('#lookahead_member_id').val( ui.item.id );
    return true;
}

// homepage slider/cycle banner
$(document).ready(function(){

    // redefine Cycle's updateActivePagerLink function
    $.fn.cycle.updateActivePagerLink = function(pager, currSlideIndex) {
        $(pager).find('li a div').removeClass('active');
        $(pager).find('li:eq('+currSlideIndex+') a div.block').addClass('active');
    };

    $('#slideshow').cycle({
        fx:     'scrollLeft',
        speed:  'slow',
        timeout: 7500,
        pager:  '#banner',
        pagerAnchorBuilder: function(idx, slide) {
            // return sel string for existing anchor
            return '#banner li:eq(' + (idx) + ') a';
        }
    });

    $('#slideshow img').click(function (){
        document.location.href = jQuery(this).attr('rel');
    }).css('cursor', 'pointer');

});

$(document).ready(function() {
    $('#showmeta').click(function() {
        $('#meta').slideToggle('slow', function() { });
        $('#hidemeta').toggle();
        $('#showmeta').toggle();
    });
    $('#hidemeta').click(function() {
        $('#meta').slideToggle('slow', function() { });
        $('#hidemeta').toggle();
        $('#showmeta').toggle();
    });

    $('a[href="#meta"]').click(function() {
        if ($('#hidemeta').css('display') != 'inline') {
            $('#showmeta').click();
        }
        return false;
    });
});
$(document).ready(function() {
  $('.resource_tooltip').cluetip({
    attribute:        'id',
    hoverClass:       'default',
    width:            300,          // The width of the clueTip
    positionBy:       'fixed',      // Sets the type of positioning - 'auto', 'mouse', 'bottomTop', 'fixed'
    topOffset:        0,          // Number of px to offset clueTip from top of invoking element. "auto", "mouse", and "bottomTop"
    leftOffset:       -340,           // Number of px to offset clueTip from left of invoking element . "auto", "mouse", and "bottomTop"
    showTitle: true, // hide the clueTips heading
    cluetipClass:     'default',// class added to outermost clueTip div in the form of 'cluetip-' + clueTipClass
    waitImage:        true,     // whether to show a loading img, which is set in jquery.cluetip.css
    arrows:           true,    // if true, displays arrow on appropriate side of clueTip
    dropShadow:       true,         // set to false if you do not want the drop-shadow effect on the clueTip
    dropShadowSteps:  3,            // adjusts the size of the drop shadow
    sticky:           true,    // keep visible until manually closed --> when true with dropshadow as true, there will
                                // be a rendering artifact of shadow before tooltip on display
    closePosition:    'title',    // location of close text for sticky cluetips; can be 'top' or 'bottom' or 'title'
    closeText:        '(Close)',  // text (or HTML) to to be clicked to close sticky clueTips
    hoverIntent: {
                      sensitivity:  3,
                      interval:     100,
                      timeout:      50
    },



    // effect and speed for opening clueTips
    fx: {
                  open:       'fadeIn', // can be 'show', 'slideDown' or 'fadeIn'
                  openspeed:  '0'
    },

// function to run just before clueTip is shown.
    onActivate:       function(e) {return true;},

    // whether to cache results of ajax request to avoid unnecessary hits to server
    ajaxCache:        true


  });

  $('.inline_tooltip').cluetip({
    attribute:        'id',
    splitTitle: " | ",
    hoverClass:       'default',
    width:            300,          // The width of the clueTip
    positionBy:       'fixed',      // Sets the type of positioning - 'auto', 'mouse', 'bottomTop', 'fixed'
    topOffset:        30,          // Number of px to offset clueTip from top of invoking element. "auto", "mouse", and "bottomTop"
    leftOffset:       -320,           // Number of px to offset clueTip from left of invoking element . "auto", "mouse", and "bottomTop"
    showTitle: true, // hide the clueTips heading
    cluetipClass:     'default',// class added to outermost clueTip div in the form of 'cluetip-' + clueTipClass
    waitImage:        true,     // whether to show a loading img, which is set in jquery.cluetip.css
    arrows:           true,    // if true, displays arrow on appropriate side of clueTip
    dropShadow:       true,         // set to false if you do not want the drop-shadow effect on the clueTip
    dropShadowSteps:  5,            // adjusts the size of the drop shadow
    sticky:           false,    // keep visible until manually closed --> when true with dropshadow as true, there will
                                // be a rendering artifact of shadow before tooltip on display
    closePosition:    'title',    // location of close text for sticky cluetips; can be 'top' or 'bottom' or 'title'
    closeText:        '<img src="/lib/images/icons/close.png" />',  // text (or HTML) to to be clicked to close sticky clueTips
    hoverIntent: {
                      sensitivity:  3,
                      interval:     100,
                      timeout:      50
    },



    // effect and speed for opening clueTips
    fx: {
                  open:       'fadeIn', // can be 'show', 'slideDown' or 'fadeIn'
                  openspeed:  '100'
    }

// function to run just before clueTip is shown.
//    onActivate:       function(e) {return true;},

    // whether to cache results of ajax request to avoid unnecessary hits to server
    //ajaxCache:        true


  });


});

Vri.imageEditor = {

    show: function(filename) {
        $.fancybox({
            'width'				: 700,
            'height'			: 595,
            'transitionIn'		: 'none',
            'transitionOut'		: 'none',
            'enableEscapeButton' : true,
            'href'              : '/member/manage-profile-image',
            //'type'				: 'ajax',
            'type'				: 'iframe',
            'showCloseButton'   : false
        });
    }
}
