/*
 * Browser Detection
 */

var BrowserDetect={init:function(){this.browser=this.searchString(this.dataBrowser)||"An unknown browser";this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"an unknown version";this.OS=this.searchString(this.dataOS)||"an unknown OS";},searchString:function(data){for(var i=0;i<data.length;i++){var dataString=data[i].string;var dataProp=data[i].prop;this.versionSearchString=data[i].versionSearch||data[i].identity;if(dataString){if(dataString.indexOf(data[i].subString)!=-1)return data[i].identity;}else if(dataProp)return data[i].identity;}},searchVersion:function(dataString){var index=dataString.indexOf(this.versionSearchString);if(index==-1)return;return parseFloat(dataString.substring(index+this.versionSearchString.length+1));},dataBrowser:[{string:navigator.userAgent,subString:"Chrome",identity:"Chrome"},{string:navigator.userAgent,subString:"OmniWeb",versionSearch:"OmniWeb/",identity:"OmniWeb"},{string:navigator.vendor,subString:"Apple",identity:"Safari",versionSearch:"Version"},{prop:window.opera,identity:"Opera"},{string:navigator.vendor,subString:"iCab",identity:"iCab"},{string:navigator.vendor,subString:"KDE",identity:"Konqueror"},{string:navigator.userAgent,subString:"Firefox",identity:"Firefox"},{string:navigator.vendor,subString:"Camino",identity:"Camino"},{string:navigator.userAgent,subString:"Netscape",identity:"Netscape"},{string:navigator.userAgent,subString:"MSIE",identity:"Explorer",versionSearch:"MSIE"},{string:navigator.userAgent,subString:"Gecko",identity:"Mozilla",versionSearch:"rv"},{string:navigator.userAgent,subString:"Mozilla",identity:"Netscape",versionSearch:"Mozilla"}],dataOS:[{string:navigator.platform,subString:"Win",identity:"Windows"},{string:navigator.platform,subString:"Mac",identity:"Mac"},{string:navigator.userAgent,subString:"iPhone",identity:"iPhone/iPod"},{string:navigator.platform,subString:"Linux",identity:"Linux"}]};BrowserDetect.init();
var browser = BrowserDetect.browser + " " + BrowserDetect.version; // returns Explorer 6 or Explorer 7
var os = BrowserDetect.OS;

$(document).ready(function(){
	
	
	//Fanyzoom for profile picture
		$.fn.fancyzoom.defaultsOptions.imgDir= base_url + 'application/veramiko/fancyzoom/img/'; 
		//very important must finish with a /

	$('.profilePhotoZoom').fancyzoom();
	

	// show news
	$("#news").show();
		
	//jQuery('#leftBarBorder').corner();
	//$("#application_wrapper .outer_wrapper .leftCorner").corner("bl 10px");
	//$("#application_wrapper .outer_wrapper .rightCorner").corner("br 10px");
	
	jQuery('a[rel*=dialog]').facebox(); 
	jQuery('a[rel*=facebox]').facebox();
	
	if(language == "es")
	{
	    var lang_text = "Idioma";
	    var apps_text = "Aplicaciones";
	    var is_text = "está";
	    var advanced_text = "Avanzada";
	    var my_account_text = "Configurar cuenta";
	}
	else if(language == "en"){
	    var lang_text = "Language";
	    var apps_text = "Applications";
	    var is_text = "is";
	    var advanced_text = "Advanced";
	    var my_account_text = "Account Settings";
	}
		
	var view = $("#view").html();
		
	/*
	
	// send applications menu to the top of the page
	var application_wrapper = "<div id='application_wrapper'><div class='right'></div></div>";
	$("body").append(application_wrapper);
	$("#applicationsList").appendTo("#application_wrapper .right");
    
    $("#application_wrapper").prepend("<img src='"+base_url+"application/veramiko/images/gray_k.png' style='float:left'/>")
    
    // all apps
    var apps = $("#applicationsList").html();
    $("#applicationsList").html("");
    var appSub = "<ul id='appSub' onmouseover=\"keepMenuOpen()\" onmouseout=\"hideMenu();\" style='display:none'>"+apps+"</ul>";

    // get searchbox
    var searchSub = "<div id=\"searchSub\">"+$("#serchBox div:first ul").html()+"</div>";
    $("#serchBox div:first").remove();
    $("#serchBox label:first").remove();
    var searchBox = $("#serchBox").html();

    // get user status
    $("#searchGlobalFrm div:eq(1) br").remove();
    var userstatus = "<span id='ss'>"+$("#searchGlobalFrm div:eq(1)").html()+"</div>";
    //var userstatus = "";

    // get my_account (username,account,privacy,logout)
	var name = $("#user_name").html();
	var my_account = $("#comnLink ul.clearAfter");
	my_account.attr("id","my_account");
	
	// remove the | from elements
	if($("#my_account li:eq(1)").html()!=null)
	{
	    $("#my_account li:eq(1)").html($("#my_account li:eq(1)").html().replace(" |",""));
	    $("#my_account li:eq(2)").html($("#my_account li:eq(2)").html().replace(" |",""));
	}
    
    // add my account to application bar
    my_account.appendTo("#application_wrapper");
	
	// remove name and account menu from existing layout
	$("#comnLink ul.clearAfter").remove();
	$("#user_name").remove();

    // get home link and move it to the application list
    if($("#my_account li:eq(1)").html()!=null)
	{
	    var home = $("#my_account li:first").html().replace(" |","");
	    $("#my_account li:first").remove();
	    $("#applicationsList").prepend("<li id='homeLink'>"+home+"</li>");
	}

    // get lang
    var lang = $("#my_account li:last").html();
    $("#my_account li:last").remove();

    // get my_account options
    var accountSub = "<ul id='accountSub' onmouseover=\"keepMenuOpen()\" onmouseout=\"hideMenu();\" style='display:none'>"+$("#my_account").html()+"</ul>";
    $("#my_account li").remove();

    // add name to my_account
	$("#my_account").append("<li id='userName'><a href='"+base_url+"profile/'>"+name+"</a>, "+is_text+" "+userstatus+"</li>");

    // get profile link and move it to the application list
    var profile = $("#siteNaviLink ul.clearAfter li:first").html();
    $("#siteNaviLink ul.clearAfter li:first").remove();
	$("#homeLink").after("<li id='profileLink' onmouseout='hideMenu();' onmouseover=\"showMenu('accountSub');\">"+profile+accountSub+"</li>");
    
    // move logout
    $("#accountSub li:last").appendTo("#applicationsList");
    
    // move search
	$("#my_account").append("<li id='searchLink'><form id=\"searchGlobalFrm\" action=\""+base_url+"search/all\" method=\"post\">"+searchBox+"</form></li>");
    $("#searchLink .cursorBtn").attr("src",base_url+"application/veramiko/images/global_search_btn.png");
   
    // get edit link and move it to my_account
    var edit = $("#siteNaviLink ul.clearAfter li:first").html();
    $("#siteNaviLink ul.clearAfter li:first").remove();

    // get friends li content and move it to the application list
    var friends = $("#siteNaviLink ul.clearAfter li:first").html();
    $("#siteNaviLink ul.clearAfter li:first").remove();
	$("#profileLink").after("<li id='friendsLink' onmouseout='hideMenu();' onmouseover=\"showMenu('friendsSub');\">"+friends+"</li>");

    // get network li content
    var network = $("#siteNaviLink ul.clearAfter li:first").html();
    $("#siteNaviLink ul.clearAfter li:first").remove();

    // get inbox li content and move it to the application list
    var inbox = $("#siteNaviLink ul.clearAfter li:first").html();
    $("#siteNaviLink ul.clearAfter li:first").remove();
	$("#friendsLink").after("<li id='inboxLink' onmouseout='hideMenu();' onmouseover=\"showMenu('inboxSub');\">"+inbox+"</li>");

    // insert all apps
    $("#inboxLink").after("<li id='appLink' onmouseout='hideMenu();' onmouseover=\"showMenu('appSub');\"><a class='naviDownArrow'>"+apps_text+"</a>"+appSub+"</li>");

    // insert account sub
    //$("#appLink").after("<li id='accountLink' ><a class='naviDownArrow'>"+my_account_text+"</a>"+accountSub+"</li>");
    
    // move edit link
    $("#accountSub").prepend("<li id='editLink'>"+edit+"</li>");
	
    // move lang link to the application list
	$("#appLink").after("<li id='langLink' class='last'>"+lang_text+": "+lang+"</li>");

    // move network li to the my account
	$("#langLink").before("<li id='networkLink' onmouseout='hideMenu();' onmouseover=\"showMenu('networkSub');\">"+network+"</li>");
        
    // remove empty
    $("#headerNavi").remove();
    
    // format footer
    $("#footer").html("<div id='footer_bar'>"+$("#footer").html()+"</div>");
	$("#footer").append("<img src='"+base_url+"application/veramiko/images/footer_logo.png' />");

	// remove left bar
	$("#leftBar").remove();
	$("#leftBarBorder").append("<div id='leftBar'></div>");
	
	*/
	
	// change notes link to my blog
	$("a.noteLeftIcon").attr("href",base_url+"notes/userNotes/");

    // obtain url
    var hash = location.href;

    // actions for different pages
    if(hash.indexOf("k")!=(-1))
	{
    }
    
	if(hash.indexOf("welcome")!=(-1))
	{
	    $('#photosadmin').cycle(
         'fade'
        );
    	
	    // move searchbox to right column
	    /*
	    var search_title = '<div class="mainInnerRightTitle"><ul class="clearAfter"><li><p>Busca</p></li></ul></div>';
        $("#mainInnerRight").prepend("<div class=\"mainInnerBox\">"+search_title+"<div class=\"statusUpdate\"><ul><li id='searchLink2'><form id=\"searchGlobalFrm2\" action=\""+base_url+"search/all\" method=\"post\">"+searchBox+"</form></li></ul></div></div>");
        $("#searchLink2").after("<ul style='position:relative;'><li id='advsearchLink' \">"+searchSub+"</li></ul>");
        
	    
	    $(".mainInnerBtmDiv div:eq(1)").css("padding-left","65px");
	    $(".mainInnerBtmDiv div:eq(1)").css("background","transparent url('"+base_url+"application/images/friendSrchIconM.gif') no-repeat scroll left 5px");
	    */
	}
	else if(hash.indexOf("home") !=(-1)) {
	    /*
		     $('#photosadmin').cycle({ 
             fx:   'scrollRight', 
            
             delay: -2000,
			  next:   '#nextPhotos', 
            prev:   '#prevPhotos' 
         });
		 */
		 
		 $('#photosadmin').cycle({ 
                  fx: 	'scrollHorz',
                  speed: 	'fast', 
                  timeout: 0, 
                  next:   '#nextPhotos', 
                  prev:   '#prevPhotos' 
          });
	} 
	else if(hash.indexOf("photosadmin") !=(-1)) {
	     $('#photosadmin').cycle({ 
             fx:   'scrollRight', 
            
             delay: -2000,
			  next:   '#nextPhotos', 
            prev:   '#prevPhotos' 
         });

		 
	/*
    $("#nextPhotos").mouseover(function(){ 
        var src = $("#nextPhotos img").attr("src");
        var new_src = src.replace("unselected","selected");
        $("#nextPhotos img").attr("src",new_src);
    });
    
    $("#nextPhotos").mouseout(function(){ 
        var src = $("#nextPhotos img").attr("src");
        var new_src = src.replace("selected","unselected");
        $("#nextPhotos img").attr("src",new_src);
    });

    */
		 
	}
	else if((hash.indexOf("profile") !=(-1))&&(hash.indexOf("wall") ==(-1))&&(hash.indexOf("search") ==(-1))) {
	    
	    // DESCOMENTAR
	    //$(".itemContent .userPic").corners("5px");
	    
	    /*
	    $(".cursorBtn").css("color","#002698");
    	$("#leftBar").css("border-left","1px #ccc solid");
    	$("#postToProfileForm").css("font-size","9px");
    	$("#leftBar").css("float","left");
    	
    	$("#welName h2").prependTo("#prflInfoCol").css("font-size","20px").css("color","#233756").css("font-weight","normal");
        if($("#prflInfoCol h2").html()!=null){ $("#prflInfoCol h2").html($("#prflInfoCol h2").html().replace("!!!","")); }
	    $("#grayBoxMain").remove();
	    
	    
	    //$("#profileInner").append("<div id='rightCol'></div>");

    	//$("#prflPhotoCol #inner #1").appendTo("#rightCol");
    	$("div#prflFriendsList .clearAfter .floatLeft a.redNormalLink").parents("div.groupItemLeft").children("div.itemHeader").children("a").before($("div#prflFriendsList .clearAfter .floatRight a.redNormalLink"));
    	$("div#prflFriendsList .clearAfter .floatLeft a.redNormalLink").parents("div.groupItemLeft").children("div.itemHeader").children("a:first").css("right","auto");
    	$("div#prflFriendsList .clearAfter .floatLeft a.redNormalLink").parents("div.groupItemLeft").children("div.itemHeader").children("a:first").css("padding-left","10px");
    	$("div#prflFriendsList .clearAfter .floatLeft a.redNormalLink").remove();
    	$("div#prflFriendsList .clearAfter .floatRight a.redNormalLink").remove();

    	//$("#prflPhotoCol #inner #2").appendTo("#rightCol");
    	$("#2 div.itemHeader a").before($("#2 div#prflFriendsList .clearAfter .floatRight a.redNormalLink"));
    	$("#2 div.itemHeader a:first").css("right","auto");
    	$("#2 div.itemHeader a:first").css("padding-left","10px");
    	$("#2 div#prflFriendsList .clearAfter .floatLeft a.redNormalLink").remove();
    	$("#2 div#prflFriendsList .clearAfter .floatRight a.redNormalLink").remove();

    	//$("#prflPhotoCol #inner #3").appendTo("#rightCol");
    	$("#3 div.itemHeader a").before($("#3 div#prflFriendsList .clearAfter .floatRight a.redNormalLink"));
    	$("#3 div.itemHeader a:first").css("right","auto");
    	$("#3 div.itemHeader a:first").css("padding-left","10px");
    	$("#3 div#prflFriendsList .clearAfter .floatLeft a.redNormalLink").remove();
    	$("#3 div#prflFriendsList .clearAfter .floatRight a.redNormalLink").remove();
	    
	    $("a.closeEl").click(function(e){
	       //$("a.closeEl").parents("div").parents("div").toggle(); 
	    });
	    
	    //$("#uploadPrflPic").appendTo("#prflPhotoCol");
	    
	    // The Wall
	    $("#WallContentLists .postInfoBox .postInfo .floatLeft:odd").css("float","right");
	    $("#WallContentLists .postInfoBox .postInfo .floatLeft:odd").css("text-align","right");
	    $("#WallContentLists .postInfoBox .postInfo .floatLeft:odd").css("background","url('"+base_url+"application/images/message_quote_right.gif') no-repeat left top");
	    $("#WallContentLists .postInfoBox .postInfo .postInfoRight:odd").css("margin-left","0px");
	    $("#WallContentLists .postInfoBox .postInfo .postInfoRight:odd").css("margin-right","60px");
	    
	    // Getting modules View all links
	    $(".rowLines li.clearAfter .floatRight a").each(function(i){
	        this.id = "viewall_"+i;
	        var link = $("#viewall_"+i).parents("div.itemContent").children(".prflRightBox").children(".prflRightInBox").children("ul.rowLines:first").children("li:first").children("p.floatRight").html();
	        $("#viewall_"+i).parents(".rowLines").addClass("rowLinesRemove");
	        $("#viewall_"+i).parents("div.itemContent").prev("div.itemHeader").children("a:first").before(link);
	        $("#viewall_"+i).css("padding-left","10px");
	        $("#viewall_"+i).css("right","auto");
	        $("#viewall_"+i).addClass("redNormalLink");
	    });
	    
	    // Getting modules View all texts
	    $(".rowLines li.clearAfter .floatLeft").each(function(i){
	        this.id = "viewall_text_"+i;
	        var text = $("#viewall_text_"+i).html();	        
	        $("#viewall_"+i).append(" ("+text+")");
	    });

        // Remove texts
	    $(".rowLinesRemove li.clearAfter").remove();
	    
	    // Friends profile module
	    //$("#prflFriendsList .topSpaceSmall li").children("a").css({ display:"block", border:"1px solid #e5e5e5", height:"55px", textAlign:"center", verticalAlign:"middle" })
	    */
	    /*
	    $("#prflFriendsList .topSpaceSmall li").each(function(i){
	        this.id = "friend_in_module_"+i;
	        var height_image = $("#friend_in_module_"+i).children("a").children("img").css("height");
	        var aux = height_image.split("px");
	        height_image = parseFloat(aux[0]);
	        var original_height = parseFloat("55");
	        var padding_top = (original_height - height_image) / 2;
	        $("#friend_in_module_"+i+" a img").css("padding-top",padding_top+"px");
	    });
	    */
	}
	else if(hash.indexOf("editProfile") !=(-1)) {


    }
    else if(hash.indexOf("message") != (-1)) {
        $("#inBoxEditSec").prependTo(".mainInnerCommon");
    }
    else if(hash.indexOf("notes") != (-1))
    {
        var x = replaceURLWithHTMLLinks($("#main").html());
        $("#main").html(x);
        var x2 = replaceURLWithHTMLLinks2($("#main").html());
        $("#main").html(x2);
    }
    

	$('#news').cycle({ 
            fx: 	'scrollHorz',
            speed: 	'fast', 
            timeout: 0, 
            next:   '#next', 
            prev:   '#prev' 
    });
    
    $("#next").mouseover(function(){ 
        var src = $("#next img").attr("src");
        var new_src = src.replace("unselected","selected");
        $("#next img").attr("src",new_src);
    });
    
    $("#next").mouseout(function(){ 
        var src = $("#next img").attr("src");
        var new_src = src.replace("selected","unselected");
        $("#next img").attr("src",new_src);
    });

    $("#prev").mouseover(function(){ 
        var src = $("#prev img").attr("src");
        var new_src = src.replace("unselected","selected");
        $("#prev img").attr("src",new_src);
    });
    
    $("#prev").mouseout(function(){ 
        var src = $("#prev img").attr("src");
        var new_src = src.replace("selected","unselected");
        $("#prev img").attr("src",new_src);
    });

});

function openFile(file,div,param,loader)
{
	if(loader == null){loader = 'loader';}
	if(div==null){
		
		$.post(file,param,function(server_response){});
				
	}else{
		
		$.post(file,param,function(server_response){ $("#"+div).html(server_response); });
		
	}
}

function openFileAndReload(file,reloadFile,div,loader)
{
	if(loader == null){loader = 'loader';}
	$.post(file,param,function(server_response){ 
		openFile(reloadFile,div,'',''); 
	});
}

function toggle_menu_bullet(id){setTimeout("toggle_menu_bullet2('"+id+"');",10);}

function createDialog(d,d2,w,h,mt,mr,f,p){
		var new_div =document.createElement('div');
		new_div.id = d;
		new_div.className='dialog';
		new_div.style.display='none';
		new_div.style.width=w;
		new_div.style.height=h;
		new_div.style.top='50%';
		new_div.style.left='50%';
		new_div.style.margin=mt+" auto auto "+mr;
		new_div.style.textAlign='center';
		new_div.style.zIndex='110';
		document.getElementById('extras').appendChild(new_div);
		var new_div2 =document.createElement('div');
		new_div2.id = d2;
		document.getElementById(d).appendChild(new_div2);

		openFile(f,d,p);
		new Effect.Appear('overlay', {duration:.3, from: 0.0, to: 0.5 });
		new Effect.Appear(d,{delay:.3,duration:.3});

}

function cancelDialog(d){
		new Effect.Fade('overlay', {delay:.3, duration:.3});
		new Effect.Fade(d,{duration:.3});

		var parent_div = document.getElementById('extras');
		parent_div.removeChild(document.getElementById(d));


}


function fontresize(numero)
{
	var elementos = Array('bullet','body');
	var sizes = Array('25px','21px','14px','11px');
	for(var i=0; i<elementos.length; i++)
	{
		if(document.getElementById(elementos[i])){
			var x = document.getElementById(elementos[i]).style.fontSize;
			if(x==''){x=sizes[i];}
			var actual_size = Number(x.split("px")[0]);
			var new_size = actual_size + numero;
			document.getElementById(elementos[i]).style.fontSize=new_size+'px';
		}
	}
}


        

		
	function check_chars(char_id,chargroup_id,condition)
	{
		
		var is_selected = $("#"+char_id+"_chars:checked").length;
		
		if(is_selected==0){
			var valid = true;
		}else{
			var how_many_selected = $(".chargroup"+chargroup_id+":checked").length;
			var valid = eval(how_many_selected+condition);
			if(condition=="") {valid=true;}
		}

		if(valid==true){
			var business_id = $("#business_id").val();
			var url = "businesses/save_chars/"+business_id+"/"+char_id+"/";
			$.get(base_url+url,"",function(response){

				//$('#'+type+"_dropdown").html(response);

			});
			
		}else{
			
			$("#"+char_id+"_chars").each(function(){
				this.checked = false;
			});
			
			alert("Ya se llego al numero maximo de opciones seleccionadas de este grupo.");
			
			//$("#"+char_id+"_chars").checked=false;
		}
	}
	
	function removeElement(div)
	{
		$("#"+div).remove();
	}
	



    function formatCurrency(num) {
    	num = num.toString().replace(/\$|\,/g,'');
    	if(isNaN(num)){
    		num = "0";
    	}
    	sign = (num == (num = Math.abs(num)));
    	num = Math.floor(num*100+0.50000000001);
    	cents = num%100;
    	num = Math.floor(num/100).toString();
    	if(cents<10){
    		cents = "0" + cents;
    	}
    	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++){
    		num = num.substring(0,num.length-(4*i+3))+','+
    	num.substring(num.length-(4*i+3));
    	}
    	return (((sign)?'':'-') + '$' + num + '.' + cents);
    }
    
    
    function ajax_form_submit(form_id, div_id){
        var url= $('#'+form_id).attr('action');
        var params = $('#'+form_id).serialize();
        $.post(url, params, function(response){ $('#'+div_id).html(response); });
    }

    function checkFilePhoto(aux,field_id)
    {
        var my_array = aux.split(".");
        var extension = my_array[my_array.length-1];
        if((extension!="jpg")&&(extension!="JPG")&&(extension!="jpeg")&&(extension!="JPEG"))
        {
            alert("Alerta! Favor de seleccionar una imagen de tipo JPG.");
            $("#"+field_id).val("");

        }
    }
    
    function replaceURLWithHTMLLinks(text) {
        //var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; //bueno
        var exp = /(\b[^'"](https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])\b/gi; //bueno
        var aux = text.match(exp);
        if(aux){
        for (var i=0; i < aux.length; i++) {
            var aux2 = aux[i].replace(/^\s*|\s*$/g,'');
            //alert("--"+aux2+"--");
            text = text.replace(aux2,"<a target='_blank' href='"+aux2+"'>"+aux2+"</a>");
        };
        }
        return text;
        //return text.replace(exp,"<a target='_blank' href='$1'>$1</a>"); 
    }
    
    function replaceURLWithHTMLLinks2(text) {
        var exp = /([^http:\/\/](www\.|ftp\.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])\b/gi; //bueno
        //var exp = /(\b(www\.|ftp\.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; //bueno
        var aux = text.match(exp);
        if(aux){
        for (var i=0; i < aux.length; i++) {
            var aux2 = aux[i].replace(/^\s*|\s*$/g,'');
            //alert("--"+aux2+"--");
            text = text.replace(aux2,"<a target='_blank' href='http://"+aux2+"'>"+aux2+"</a>");
        };
        }
        return text;
        //return text.replace(exp,"<a target='_blank' href='http://$1'>$1</a>"); 
    }
