/**
    Detect browser version
*/
function documentClass() {
    // Tell the CSS that the JavaScript is initialized
    document.documentElement.className += ' js';

    // For easy CSS browser detection
    if (jQuery.browser.msie) {
        var v = parseFloat(jQuery.browser.version),
            n = [5.5, 6, 7],
            c = ' ie ie'+v;
        // Add the ieN-down and ieN-up classes
        for (var i = n.length-1; i >= 0; --i) {
            if (n[i] >= v) {
                c += ' ie'+n[i]+'-down';
            }
            if (n[i] <= v) {
                c += ' ie'+n[i]+'-up';
            }
        }
        document.documentElement.className += c.replace('.', '');
    } else if (jQuery.browser.mozilla) {
        document.documentElement.className += ' mozilla';
    } else if (jQuery.browser.safari) {
        document.documentElement.className += ' safari';
    } else if (jQuery.browser.opera) {
        document.documentElement.className += ' opera';
    }
}
documentClass();

/**
    Make avatar menu widget
*/
function avatarWidgets() {
	$("div.avatar").each(function() {
		$(this).click(function(event) {
			$(this).next("div.avatar-menu").toggle();
			return false;
		});
	});

	$("a.avatar-menu-close").each(function() {
		$(this).click(function(event){
			$(this).parent().parent().parent().hide();
			return false;
		});
	});
};

/**
	Make help
*/
function help() {
	$(".show-help").click(function(){
		var id = $(this).attr("rel");
		$("#"+id).fadeIn();
		return false;
	});

	$(".close-help").click(function(){
		$(this).parent().fadeOut();
		return false;
	});
}

/**
    Make tooltips
*/
function toolTips() {
	$(".tooltip").each(function() {
		if (this.title == '')
			return false;
		else {
			var tip = document.createElement('div');
			var offsetX = -32;
			var offsetY = 12;
			$(tip).addClass("tip").append("<p class='text-s'>" + this.title + "</p><span class='tip-bottom'><!-- --></span>").hide();
			$("body").append($(tip));
			$(this).removeAttr("title").hover(function() {
				$(tip).show();
				$().mousemove(function(e){
					$(tip).css({left: (e.pageX+offsetX) + "px", top: (e.pageY+offsetY) + "px"});
					return false;
				});
				return false;
			},function(){
				$(tip).hide();
				return false;
			});
		};
	});
	return false;
};


/**
    Transform an URL for AJAX usage
    It transforms /example/path?foo=bar into /example/path/ajax?foo=bar&rand=1234
*/
function ajax_link(url) {
    var urlParts = url.split('?');
    var url = urlParts[0];

    var d = new Date();
    var time = d.getTime();
    var arg = (urlParts.length > 1) ? '?'+urlParts[1]+'&amp;' : '?';
    arg += 't='+time;

    //if (url.charAt(url.length-1) != '/')
    //    url += '/';

    return url+arg;
}

/**
	Ajax method that displays the "choose groups" window for post or photos.
	Also manage the submit of this window.
*/
function show_send_group_menu(item_id, item_type, target_id, main_block_id, list_or_block) { // item_type: either "post" or "photo"
    $("#"+target_id).show().css("background","white url(/media/images/loading.gif) center center no-repeat");
    $.ajax({
        url: ajax_link("/you/ajax_"+item_type+"_groups/"+item_id+"/?list_or_block="+list_or_block),
        type: "GET",
        error: function(){
            alert("Reload group: Error loading data from server:"+"/you/ajax_"+item_type+"_groups/"+item_id+"/");
        },
        success: function(html){
            $("#"+target_id).css("background","#F6F6F6").show().html(html);

            var options = {
			    success: function(html) {
			    	if (list_or_block == 'list'){
			    		$("#"+item_type+"-groups-"+item_id).remove();
	                    $("#"+main_block_id).append(html); //append the updated list
	                }
	                else {
						$("#"+main_block_id).html(html);
	                }
                }
			};

			$("#groups_form_"+item_id).submit(function() {
			    $(this).ajaxSubmit(options);
			    $("#"+target_id).hide();
			    return false;
			});
        }
    });
    return false;
}


/*
	Ajax method that manage the "remove" post or photo from group link.
*/
function remove_item_from_group(item_id, item_type, group_id, main_block_id, base_url, link_id, list_or_block) {
    $("#"+link_id).attr({ href: "#" }); // ajax running: no need to reload the whole page
    $.ajax({
        url: ajax_link(base_url+"?"+item_type+"_id="+item_id+"&group_id="+group_id + "&list_or_block=" + list_or_block),
        type: "POST",
        error: function(){
            alert("Update list of groups: Error loading data from server: "+base_url+"?"+item_type+"_id="+item_id+"&group_id="+group_id + "&list_or_block=" + list_or_block);
        },
        success: function(html){
            if (list_or_block == 'list'){
    			$("#"+item_type+"-groups-"+item_id).remove();
                $("#"+main_block_id).append(html); //append the updated list
            }
            else {
				$("#"+main_block_id).html(html);
            }
        }
    });
    return false;
}


/**
	Ajax method that update the group categories.
*/
function update_group_categories(cat_filter) {
    var url = '/you/ajax_update_category/'
    if (cat_filter!='-100'){
    	url +='?category='+cat_filter;
    }
    $.ajax({
        url: ajax_link(url),
        type: "POST",
        error: function(){
            alert("Update list of categories: Error loading data from server");
        },
        success: function(html){
            $("#user_categories").html(html); //append the updated list
        }
    });
}


/**
	Ajax method that displays the "choose categories" window for groups.
	Also manage the submit of this window.
*/
function show_send_category_menu(item_id, item_type, target_id, main_block_id, cat_filter) { // item_type: group
    hide_group=false;
    $("#"+target_id).show().css("background","white url(/media/images/loading.gif) center center no-repeat");
    $.ajax({
        url: ajax_link("/you/ajax_"+item_type+"_categories/"+item_id+"/?cat_id="+cat_filter),
        type: "GET",
        error: function(){
            alert("Reload categories: Error loading data from server:"+"/you/ajax_"+item_type+"_categories/"+item_id+"/");
        },
        success: function(html){
            $("#"+target_id).css("background","#F6F6F6").show().html(html);
			$("#categories_form_"+item_id).submit(function() {

				var options = {
					beforeSubmit: function(formArray, jqForm) {
						if (cat_filter!='-100' && cat_filter!='admin'){
							hide_group=true;
							for (i=0;i<formArray.length;i++){
								if (formArray[i].name == "check_"+item_id+"_"+cat_filter){
									hide_group=false;
								}
							}
						}
				    },
				    success: function(html) {
				        $("#"+main_block_id).children(".categories-list").remove(); //remove the old list
	                    $("#"+main_block_id).prepend(html); //prepend the updated list
	                    if (hide_group){
			    			$("#li-group-"+item_id).slideUp("slow");
					    }
					    update_group_categories(cat_filter);
	                }
				};

			    $(this).ajaxSubmit(options);
			    $("#"+target_id).hide();
			    return false;
			});

        }
    });
    return false;
}


/*
	Ajax method that manage the "remove" group from category
*/
function remove_item_from_category(item_id, item_type, category_id, main_block_id, base_url, link_id, cat_filter) {
    //$("#"+link_id).attr({ href: "#" }); // ajax running: no need to reload the whole page
    url = base_url+"?"+item_type+"_id="+item_id+"&category_id="+category_id+"&cat_id="+cat_filter;
    hide_group=false;
    if (cat_filter!='-100' && cat_filter==category_id){
    	hide_group=true;
    }
    $.ajax({
        url: ajax_link(url),
        type: "POST",
        error: function(){
            alert("Remove item from category: Error loading data from server: "+url);
        },
        success: function(html){
            $("#"+main_block_id).children(".categories-list").remove(); //remove the old list
            $("#"+main_block_id).prepend(html); //append the updated list
        }
    });

    if (hide_group){
    	$("#li-group-"+item_id).fadeOut();
    }
    update_group_categories(cat_filter);
    return false;
}


/*
	Method that displays the "user_feedback" on the upper part of the
	screen, according to the boolean value of "is_ok" (success or fail)
*/
var show_feedback = function(user_feedback, is_ok) {
	$("#user-feedback").each(function(){
		$(this).hide();
		if(user_feedback != "") {
			if (is_ok) {
				user_feedback = '<p class="success">'+user_feedback+'</p>';
			}
			else {
				user_feedback = '<p class="fail">'+user_feedback+'</p>';
			}
			$(this).html(user_feedback);
			$(this).show();
			/*setTimeout(function() {
				$("#user-feedback").fadeOut("slow");
			}, 3000);
			*/
		}
	});
}



var closeCall;
function popupBox(link, box, callbacks) {
    var body = $('body'),
        open = false,
        close;
    link = $(link);
    box = $(box);

    // Add a close button
    box.append(close = $('<div class="close"><a href="javascript:void($(\'body\').click())"><img src="/media/images/icons/close_popup.png" alt="close" /></a></div>'));

    link.click(function() {
        if (!open) {
            open = true;
            close.show();
            // This click is used to close other such boxes that could possibly be open
            body.click();
            box.slideDown('fast', function() {
                body.click(function() {
                    open = false;
                    close.hide();
                    body.unbind('click');
                    box.slideUp('fast', function() {
                        if (callbacks && callbacks.closeEnd)
                            callbacks.closeEnd();
                    });
                    if (callbacks && callbacks.closeStart)
                        callbacks.closeStart();
                });
                if (callbacks && callbacks.openEnd)
                    callbacks.openEnd();
            });
            if (callbacks && callbacks.openStart)
                callbacks.openStart();
        }
        return false;
    });

    // Avoid that other clicks within the box closes it
    box.click(function(e) {
        e.stopPropagation();
    });
}


function styleSearch() {
    var form = $('#search-form'),
        label = $('.search label', form).hide(),
        text = label.text(),
        search = $('#'+label.attr('for'));

    if (!search.val()) {
        search.val(text);
    }

    $('fieldset span', form).each(function(i) {
        $(this).addClass(i%2 == 0 ? 'even' : 'odd');
    });

    popupBox(search, $('.popup-box', form),
        {
            openStart: function() {
                form.addClass('open');
                if(search.val() == text)
                    search.removeClass('off').val('');
            },
            closeEnd: function() {
                form.removeClass('open');
                if(search.val() == '')
                    search.addClass('off').val(text);
            }
        }
    );

    form.click(function(e) {
        e.stopPropagation();
    });
    $('.submitinput', form).click(function() {
        form.submit();
    });
}

/**
	Returns the width and the height of the browser window in an array
*/
function getWindowSize() {
	var w = 0, h = 0; s = new Array();
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		w = window.innerWidth;
		h = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		w = document.documentElement.clientWidth;
		h = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		w = document.body.clientWidth;
		h = document.body.clientHeight;
	}
	s[0] = w;
	s[1] = h;
	return s;
}

/**
	Email validation check
*/
function isValidEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(email))
      return true;
   else
	return false;
}

/**
	Check the number of characters in text field (for write headline form)
*/
function limitChars(textid, limit, infodiv, type){
	var maxChar = limit;
    var trailerLength = 0;
    var msg = textid;
    var left = infodiv;
    var msg_val = msg.val();
    var smsLenLeft = maxChar - (countSpecialChars(msg_val) + trailerLength);
    while (smsLenLeft < 0) {
    	msg_val = msg.val();
    	if (msg_val.substring(msg_val.length-4,msg_val.length)=='<br>'){
    		msg.val(msg_val.substring(0,msg_val.length-5) + '<br>');
    	}
    	else {
    		msg.val(msg_val.substring(0,msg_val.length-1));
    	}
    	smsLenLeft = maxChar - (countSpecialChars(msg.val()) + trailerLength);
    }
    left.val(smsLenLeft);
}



function countSpecialChars(message){
	var chars = new Array(/\u20AC/g,/\[/g,/\]/g,/\{/g,/\}/g,/\^/g,/\~/g,/\\/g,/\|/g,/\cJ/g,/\cI/g);
 	var msglength=0;
  	for(i=0;i<chars.length;i++){
 		matches = message.match(chars[i]);
 		if (matches!=null){
 			msglength += matches.length;
 		}
 	}
 	return message.length + msglength;
}


/**
	Set the height of a column (div) depending on the height of the browser window.
	Used on the feeds page for making the left column scrollable.
*/
function setColumnHeight(target, t) {
	/* t = height from top of browser window to top of column */
	var h = (getWindowSize()[1] - t) + "px";
	$("#" + target).height(h);
	return false;
}
