$(document).ready(function(){
    checkIframeLinkedin();
    setupButtons();
    setupFields();
    bindPlansMenu();
    bindMenu();
    loadAddThis();
    scrollFollow();
    checkMoveSearch();
    setupFlashNotifications();
    setupErrorLists();
});

var focusSearch=function(mytext){
    if($("#globalSearchBoxHome").val() == mytext)$("#globalSearchBoxHome").val("");
}

var blurSearch=function(mytext){
    
    if($("#globalSearchBoxHome").val() == "")$("#globalSearchBoxHome").val(mytext);
}

var checkIframeLinkedin=function(){
    if( top.location.host.match("linkedin") != null ){
        top.location.replace(location.href); 
    }
}

var disabled = function(){
    //do nothing
    //alert("disabled");
}

var resendEmailValidator=function(id,url){
    $.ajax({
      url: url,
      success: function(){
        $('#responseAjax'+id).show();
      }
    });
}


var confirmUnregister=function(){
        var name1=$('#text1').val();
    var name2=$('#text2').val();
        $( "#unregisterDiv" ).dialog({
            resizable: true,
            width: 500,
            modal: true,
            buttons: [
                    {
                        text: name1,
                        click: function() {
                            $('#unregisterForm').submit();
                            $( this ).dialog( "close" );
                        }
                    },{
                        text: name2,
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }]

    });
}

var linkedBox=function(){
        var name1=$('#linked1').val();
    var name2=$('#linked2').val();
    $('#linkedBox').dialog({
            resizable: false,
            modal: true,
            buttons: [
                    {
                        text: name1,
                        click: function() {
                            $('#linkedForm').submit();
                            $( this ).dialog( "close" );
                        }
                    },{
                        text: name2,
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }]

    });
}

var alertEnglish=function(){
    if($('#english_is').val() == 0){
        $('#text_english_is a').button();
        $('#text_english_is').show();
        $('#english_is').val(1);
    }else{
        $('#text_english_is').hide();
    }
}

var showATInfo = function(){
    $('#aboutThis').dialog({
        modal:true,
        show: 'slide',
        dialogClass: 'alert'
    });
}


var makeRFI=function(){
    var name1=$('#text1').val();
    var name2=$('#text2').val();
    $( "#myRFI").dialog({
            resizable: true,
            width: 660,
            modal: true,
            buttons: [
                    {
                        text: name1,
                        click: function() {
                            $('#myRFIform').submit();
                            $( this ).dialog( "close" );
                        }
                    },{
                        text: name2,
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }]

    });

}


var setAdvSearch=function(){
    var v;
    $('form#topSearchForm').find("input[name=type_search]").each(function(){
        if ( $(this).is(":checked") )
            v= $(this).val();
    });
    if(v!= -1)toggleFilterTypeSearch('type_search_a'+v);
    
    $('form#topAdvSearchForm').find("input[name=type_search]").each(function(){
        if ( $(this).is(":checked") && v != $(this).val() )
            $(this).removeAttr("checked","checked");
        if ( ! $(this).is(":checked") && v == $(this).val() )
            $(this).attr("checked","checked");
    });
    
    $('#advSearchBox').show();
    $('#simpleSearchBox').hide();
    
}

var unsetAdvSearch=function(i){
        var v;
    $('form#topSearchForm').find("input[name=type_search]").each(function(){
        if ( $(this).is(":checked") )
            v= $(this).val();
    });
    if(v!= -1)toggleFilterTypeSearch('type_search_a'+v);
    
    $('form#topAdvSearchForm').find("input[name=type_search]").each(function(){
        if ( $(this).is(":checked") && v != $(this).val() )
            $(this).removeAttr("checked","checked");
        if ( ! $(this).is(":checked") && v == $(this).val() )
            $(this).attr("checked","checked");
    });
    
    $('#advSearchBox').hide();
    $('#simpleSearchBox').show();
}


var moreExamples=function(id){
        $('#error_explain_'+id).dialog({
			show: "blind",
                        hide: "blind",
                        modal: true
		});
}

var showInnogetAgreement=function(){


    $('#innoget_agreement_text').dialog({
			show: "blind",
                        hide: "blind",
                        modal: true,
                        width: 700
		});
}

var changeOrgType=function(){
    if($('#organization_type').val()=="5"){
        $('#organization_role').val('7');
        $('.p_hide').hide();
    }else{
        $('.p_hide').show();
    }
};


var explain=function(id){
    $('#'+id+'_explain').dialog({
			show: "blind",
                        hide: "blind",
                        modal: true
		});
}

/* NEW fastRegister y fastLogin*/

var fastRegister_OLD = function(){
    $('#fastLogin').hide();
    $('#fastRegister').show();
    var offset=$('#fastRegister').offset();
    offset.top-=80;
    $(document).scrollTo( offset );
};

var fastRegister = function(){
    if($("fastRegisterOSX").hasClass("lonely")){
        $("#fastRegisterOSX").modal({
            overlayId: 'osx-overlay',
            containerId: 'osx-containerSmallRegister',
            closeHTML: null,
            minHeight: 80,
            opacity: 65, 
            position: ['0',],
            overlayClose: true,
            onOpen: fastRegisterOSX.open,
            onClose: fastRegisterOSX.close
        });    
    }else{
        if( fastLoginOSX.started ){
            $.modal.close();
            setTimeout(function(){
                $("#fastRegisterOSX").modal({
                    overlayId: 'osx-overlay',
                    containerId: 'osx-containerLarge',
                    closeHTML: null,
                    minHeight: 80,
                    opacity: 65, 
                    position: ['0',],
                    overlayClose: true,
                    onOpen: fastRegisterOSX.open,
                    onClose: fastRegisterOSX.close
                });
            }, 1000);

        }else{
            $("#fastRegisterOSX").modal({
                    overlayId: 'osx-overlay',
                    containerId: 'osx-containerLarge',
                    closeHTML: null,
                    minHeight: 80,
                    opacity: 65, 
                    position: ['0',],
                    overlayClose: true,
                    onOpen: fastRegisterOSX.open,
                    onClose: fastRegisterOSX.close
            });    
        }
    }
};


var fastRegisterModal = function(){
    fastRegister();
};

var fastLogin_OLD = function(){
    $('#fastRegister').hide();
    $('#fastLogin').show();
    var offset=$('#fastLogin').offset();
    offset.top-=80;
    $(document).scrollTo( offset );
};

var fastLogin = function(){
    if($("#fastLoginOSX").hasClass("lonely")){
        $("#fastLoginOSX").modal({
            overlayId: 'osx-overlay',
            containerId: 'osx-containerSmall',
            closeHTML: null,
            minHeight: 80,
            opacity: 65, 
            position: ['0',],
            overlayClose: true,
            onOpen: fastLoginOSX.open,
            onClose: fastLoginOSX.close
        });   
    }else{

        if( fastRegisterOSX.started ){
            $.modal.close();
            setTimeout(function(){
                $("#fastLoginOSX").modal({
                    overlayId: 'osx-overlay',
                    containerId: 'osx-container',
                    closeHTML: null,
                    minHeight: 80,
                    opacity: 65, 
                    position: ['0',],
                    overlayClose: true,
                    onOpen: fastLoginOSX.open,
                    onClose: fastLoginOSX.close
                });        
            },1000);
        }else{
            $("#fastLoginOSX").modal({
                overlayId: 'osx-overlay',
                containerId: 'osx-container',
                closeHTML: null,
                minHeight: 80,
                opacity: 65, 
                position: ['0',],
                overlayClose: true,
                onOpen: fastLoginOSX.open,
                onClose: fastLoginOSX.close
            });    
        }
    }
};


var fastRegisterOSX = {
    started: false,
    callAlter: false,
    container: null,
    init: function () {

    },
    open: function (d) {
            var self = this;
            self.container = d.container[0];
            fastRegisterOSX.started=true;
            d.overlay.fadeIn('slow', function () {
                    $("#fastRegisterOSX", self.container).show();
                    var title = $("#osx-modal-title", self.container);
                    title.show();
                    d.container.slideDown('slow', function () {
                            setTimeout(function () {
                                    var h = $("#osx-modal-data", self.container).height()
                                            + title.height()
                                            + 20; // padding
                                    d.container.animate(
                                            {height: h}, 
                                            200,
                                            function () {
                                                    $("div.close", self.container).show();
                                                    $("#osx-modal-data", self.container).show();
                                            }
                                    );
                            }, 300);
                    });
            })
    },
    close: function (d) {
            var self = this; // this = SimpleModal object
            d.container.animate(
                    {top:"-" + (d.container.height() + 20)},
                    500,
                    function () {
                            fastRegisterOSX.started=false;
                            self.close(); // or $.modal.close();
                    }
            );
    }
};

var fastLoginOSX = {
    started: false,
    callAlter: false,
    container: null,
    init: function () {

    },
    open: function (d) {
            var self = this;
            fastLoginOSX.started=true;
            self.container = d.container[0];
            d.overlay.fadeIn('slow', function () {
                    $("#fastLoginOSX", self.container).show();
                    var title = $("#osx-modal-title", self.container);
                    title.show();
                    d.container.slideDown('slow', function () {
                            setTimeout(function () {
                                    var h = $("#osx-modal-data", self.container).height()
                                            + title.height()
                                            + 20; // padding
                                    d.container.animate(
                                            {height: h}, 
                                            200,
                                            function () {
                                                    $("div.close", self.container).show();
                                                    $("#osx-modal-data", self.container).show();
                                            }
                                    );
                            }, 300);
                    });
            })
    },
    close: function (d) {
            var self = this; // this = SimpleModal object
            d.container.animate(
                    {top:"-" + (d.container.height() + 20)},
                    500,
                    function () {
                            fastLoginOSX.started=false;
                            self.close(); // or $.modal.close();
                    }
            );
    }
};



var fastLoginModal = function(){
    fastLogin();

};

/* END fastRegister y fastLogin*/


var plansExpand= function(id){
    $('#pItem'+id).show();
    $('#pItem'+id).click(function(){
        plansCollapse(id);
    });
    $('#expand'+id).hide();
    $('#collapse'+id).show();
};

var plansCollapse= function(id){
    $('#pItem'+id).hide();
    $('#expand'+id).show();
    $('#collapse'+id).hide();
};

var toggleFilterTypeSearch= function(id){
    var a=$('#'+id).val();
    if(a==-1){
        $('.myfilterCommon').show();
        $('.myfilterDemand').hide();
        $('.myfilterOffer').hide();
    }else if(a==0){
        $('.myfilterCommon').hide();
        $('.myfilterDemand').show();
        $('.myfilterOffer').hide();
    }else if(a==1){
        $('.myfilterCommon').hide();
        $('.myfilterDemand').hide();
        $('.myfilterOffer').show();
    }
};


var viewMoreResultSearch = function(id){
    
        $("#detailsResultItem"+id).show();
        $("#viewMoreResultItem"+id).hide();
        $("#viewLessResultItem"+id).show();
};

var viewLessResultSearch = function(id){
        $("#detailsResultItem"+id).hide();
        $("#viewMoreResultItem"+id).show();
        $("#viewLessResultItem"+id).hide();
};

var sendTellAFriend=function(url){
    $.ajax({
      type: "POST",
      url: url,
      data: $('#formTellAFriend').serialize(),
      dataType: "html",
      beforeSend: function(objeto){
            $("#tellAFriendContainer").html("<center><img src='/images/loading.gif' alt=''/></center>");
      },
      success: function(msg){
            $("#tellAFriendContainer").html(msg);
            $( "button, input:submit, input:button, a", ".chatFrame" ).button();
            $('#tellAFriendButton').click(function(){
                sendTellAFriend(url);
                return false;
            });
      },
      error: function(objeto, quepaso, otroobj){
            alert("ERROR!! - "+quepaso);
            closeTellAFriend();
      }
    });
}

var tellAFriend=function(url){
        var dialogOpts = {
            modal: true,
            width: 500,
            height: 'auto',
            open: function() {
                //display correct dialog content
                $("#tellAFriendContainer").load(url, function(response, status, xhr) {
                    if (status == "error") {
                        var msg = error + " : ";
                        $("#tellAFriendContainer").html(msg + xhr.status + " " + xhr.statusText);
                    }else if(status == "success"){
                        $( "button, input:submit, input:button, a", ".chatFrame" ).button();
                        $('#tellAFriendButton').click(function(){
                            sendTellAFriend(url);
                            return false;
                        });
                    }
                });
            },
            close: function() {
                $("#tellAFriendContainer").html("<center><img src='/images/loading.gif' alt=''/></center>");
            }
        };
        $("#tellAFriendContainer").dialog(dialogOpts);    //end dialog
}

var closeTellAFriend=function(){
    $('#tellAFriendContainer').dialog('close');
}


var sendRecomendBox=function(url){
    $.ajax({
      type: "POST",
      url: url,
      data: $('#formRecomendBox').serialize(),
      dataType: "html",
      beforeSend: function(objeto){
            $("#recomendBoxContainer").html("<center><img src='/images/loading.gif' alt=''/></center>");
      },
      success: function(msg){
            $("#recomendBoxContainer").html(msg);
            $( "button, input:submit, input:button, a", ".chatFrame" ).button();
            $('#recomendBoxButton').click(function(){
                sendRecomendBox(url);
                return false;
            });
      },
      error: function(objeto, quepaso, otroobj){
            alert("ERROR!! - "+quepaso);
            closeRecomendBox();
      }
    });
}

var recomendBox=function(url){
        var dialogOpts = {
            modal: true,
            width: 500,
            height: 'auto',
            open: function() {
                //display correct dialog content
                $("#recomendBoxContainer").load(url, function(response, status, xhr) {
                    if (status == "error") {
                        var msg = error + " : ";
                        $("#recomendBoxContainer").html(msg + xhr.status + " " + xhr.statusText);
                    }else if(status == "success"){
                        $( "button, input:submit, input:button, a", ".chatFrame" ).button();
                        $('#recomendBoxButton').click(function(){
                            sendRecomendBox(url);
                            return false;
                        });
                    }
                });
            },
            close: function() {
                $("#recomendBoxContainer").html("<center><img src='/images/loading.gif' alt=''/></center>");
            }
        };
        $("#recomendBoxContainer").dialog(dialogOpts);    //end dialog
}

var closeRecomendBox=function(){
    $('#recomendBoxContainer').dialog('close');
}


var submitForm=function(id){
    $('#'+id).submit();
}




var removeAddable=function(id){
    $(id).remove();
    $(id).hide();
};


var addableSave=function(id,deletetext){
        var texto=$('#addable_text_'+id).val();
        var j=0;
        var salir=true;
        // check ids
        while(salir){
            if($('#'+id+"_"+j).length > 0)j++;
            else salir=false;
        }
        // Div contenedor
        var divC = $( document.createElement('div') );
        divC.attr({
            "class":"addable_item_added"
        })
        // input hidden
        var inputH = $( document.createElement('input') );
        inputH.attr({
            name: id+'['+j+']',
            value: texto,
            type: 'hidden',
            id: id+"_"+j
        });
        // input show
        var parP = $( document.createElement('p') );
        parP.append(texto);
        var deleteB = $( document.createElement('a') );
        deleteB.attr({
            "class": "delete_addable"
        });

        $(deleteB).click(function(){
           $(divC).remove();
           $(divC).hide();
        });


        $(deleteB).append(deletetext);
        $(deleteB).appendTo($(parP));


        $(divC).append(inputH);
        $(divC).append(parP);
        $('#addable_list_'+id+' .clearInit').remove();
        $(divC).appendTo($('#addable_list_'+id));
        //$(".delete_addable, .delete_uploaded_file").button();
}

var addAddable=function(id,oktext,okmore,canceltext,deletetext){
        $('#addable'+id).dialog({
			height: 300,
			width: 390,
			modal: true,
			buttons: [
                            {
				text: okmore,
                                click: function() {
                                    addableSave(id,deletetext);
                                    $('#addable_text_'+id).val( '' );
                                    $('#addable_text_'+id).focus();
				}
                            },
                            {
				text: oktext,
                                click: function() {
                                    addableSave(id,deletetext);
                                    $( this ).dialog( "close" );
				}
                            },{
				text: canceltext,
                                click: function() {
                                    $( this ).dialog( "close" );
				}
                            }],
			close: function() {
                            $('#addable_text_'+id).val( '' );
			}
		});
}


var controllerText=function(id){
    var v=$('#'+id).val();
    // Hacemos un stripTags cutre
    v=v.replace(/<\/?[^>]+>/gi, '');
    var i=v.length;
    var total=$('#controller'+id).attr("title");
    $('#controller'+id).text(total - i);
}

var innWindowOpen=function(url){
    window.open(url,'mywindow','width=960,height=600,location=0,status=0,menubar=0,directories=0,scrollbars=yes');
}

var setupButtons= function(){
    $(".button_ui").button();
    //$(".pAreasAdd a.add").button();
    //$(".delete_addable, .delete_uploaded_file").button();
}

var setupFields=function(){
    $('textarea.pubInputArea').autogrow();
}

var bindPlansMenu=function(){
        $('#top li.dropli ul li').css({display: "block", "float": "left", width: "150px"});
        $('#top li.dropli').hover(function(){
            $(this).find('ul:first').css({visibility: "visible",display: "block",backgroundColor:"white", width: "200px"}).slideDown(200); // effect 2
        },function(){
            $(this).find('ul:first').css({visibility: "hidden"});
        });
}

var bindMenu=function(){    
    
    var megaConfig = {
     interval: 400,
     sensitivity: 4,
     over: addMenu,
     timeout: 100,
     out: removeMenu
    }
    //$(".menuinn_home, .menuinn_demands, .menuinn_offers, .menuinn_about, .menuaccount_item_dropdown").each(function(){
    $(".menuinn_home, .menuinn_about, .menuaccount_item_dropdown").each(function(){
        $(this).hoverIntent(megaConfig);
        $(this).click(addMenuClick);
    });

    $("a.main").removeAttr("title");
}

var addMenuClick=function(){
      $(this).find('div.menuaccount_submenu').show();
      $(this).find('div.menuinn_submenu').show();
      $(this).find('a.main').addClass("mainHover");
}


var addMenu=function(){
      removeMenu2();
      $(this).find('div.menuaccount_submenu').show();
      $(this).find('div.menuinn_submenu').show();
      $(this).find('a.main').addClass("mainHover");
}

var removeMenu=function(){
      $(this).find('div.menuaccount_submenu').hide();
      $(this).find('div.menuinn_submenu').hide();
      $(this).find('a.main').removeClass("mainHover");
}
var removeMenu2=function(){
      $('a.main').each(function(){$(this).removeClass("mainHover")});
      $('div.menuaccount_submenu').each(function(){$(this).hide()});
      $('div.menuinn_submenu').each(function(){$(this).hide()});
}

var myDialog=function(id){
    $('#'+id).dialog({
			height: 500,
			width: 900,
			modal: true
                    });
}

var myToggle=function(id){
    if ( $("#"+id+"Handler").hasClass("showLessPub") ){
        $("#"+id+"Handler").removeClass("showLessPub");
        $("#"+id+"Handler").addClass("showMorePub");
    }else{
        $("#"+id+"Handler").removeClass("showMorePub");
        $("#"+id+"Handler").addClass("showLessPub");
    }
        
    $('#'+id).toggle("slow");
}

var loadAddThis=function(){
    addthis.init();    
}

var addthis_config = {"data_track_clickback":true};

var scrollFollow=function(){
    if( $("#scrollFollowParent").length > 0 ){
        var el = $('#scrollFollow');
        var offset=$("#scrollFollowParent").offset();
        var elpos_original = offset.top;
        
        $(window).scroll(function(){
            var windowpos = $(window).scrollTop();
            var finaldestination = windowpos + 30;
            if(windowpos<elpos_original) {
                finaldestination = elpos_original;
                el.stop().css({'top':10});
            } else {
                el.stop().animate({'top':finaldestination-elpos_original+10},500);
            }
        });
    }
    if( $("#scrollFollowAuto").length > 0 ){
        var el = $('#scrollFollowAuto');
        var offset= el.parent().offset();
        var elpos_original = offset.top;
        var size_max = el.parent().height() - el.height() ;
        var tmp = 0;
        $(window).scroll(function(){
            var windowpos = $(window).scrollTop();
            var finaldestination = windowpos + 30;
            if(windowpos<elpos_original) {
                finaldestination = elpos_original;
                el.stop().css({'top':10});
            } else {
                tmp = finaldestination-elpos_original+10;
                if(tmp < size_max)
                    el.stop().animate({'top': tmp},500);
                else
                    el.stop().animate({'top': size_max},500);
            }
        });
    }
}


var checkMoveSearch=function(){
    if( $("#searchConceptsBack").length > 0 ){
        $('#searchConcepts').html($("#searchConceptsBack").html());
        $("#searchConceptsBack").html("");
    }
}

var setupFlashNotifications=function(){
    if( $("#flashNotificationsWeb").length > 0 ){
        window.setTimeout(hideNotifications,10000);
    }
}

var setupErrorLists=function(){
    $("ul.error_list li").each(function(){
        if( ! $(this).hasClass("setUp") ){
            var con = $(this).text();
            $(this).text("");
            $(this).append("<span class=\"myErrorList\">"+con+"</span>");
            $(this).addClass("setUp");
        }
    });
}

var hideNotifications=function(){
    $("#flashNotificationsWebShow").show();
    $("#flashNotificationsWeb").hide("slow",function(){
        
    });
}

var showNotifications=function(){
    $("#flashNotificationsWebShow").hide();
    $("#flashNotificationsWeb").show("slow");
}



BookmarkApp = function () {
    var isIEmac = false; /*@cc_on @if(@_jscript&&!(@_win32||@_win16)&& 
(@_jscript_version<5.5)) isIEmac=true; @end @*/
    var isMSIE = (-[1,]) ? false : true;
    var cjTitle = document.title;
    var cjHref = location.href;

    function hotKeys() {
        var ua = navigator.userAgent.toLowerCase();
        var str = '';
        var isWebkit = (ua.indexOf('webkit') != - 1);
        var isMac = (ua.indexOf('mac') != - 1);

        if (ua.indexOf('konqueror') != - 1) {
            str = 'CTRL + B'; // Konqueror
        } else if (window.home || isWebkit || isIEmac || isMac) {
            str = (isMac ? 'Command/Cmd' : 'CTRL') + ' + D'; // Netscape, Safari, iCab, IE5/Mac
        }
        return ((str) ? 'Press ' + str + ' to bookmark this page.' : str);
    }

    function isIE8() {
        var rv = -1;
        if (navigator.appName == 'Microsoft Internet Explorer') {
            var ua = navigator.userAgent;
            var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
            if (re.exec(ua) != null) {
                rv = parseFloat(RegExp.$1);
            }
        }
        if (rv > - 1) {
            if (rv >= 8.0) {
                return true;
            }
        }
        return false;
    }

    function addBookmark(a) {
        try {
            if (typeof a == "object" && a.tagName.toLowerCase() == "a") {
                a.style.cursor = 'pointer';
                if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) {
                    window.sidebar.addPanel(cjTitle, cjHref, ""); // Gecko
                    return false;   
                } else if (isMSIE && typeof window.external == "object") {
                    if (isIE8()) {
                        window.external.AddToFavoritesBar(cjHref, cjTitle); // IE 8                    
                    } else {
                        window.external.AddFavorite(cjHref, cjTitle); // IE <=7
                    }
                    return false;
                } else if (window.opera) {
                    a.href = cjHref;
                    a.title = cjTitle;
                    a.rel = 'sidebar'; // Opera 7+
                    return true;
                } else {
                    alert(hotKeys());
                }
            } else {
                throw "Error occured.\r\nNote, only A tagname is allowed!";
            }
        } catch (err) {
            alert(err);
        }
        
    }
    
    return {
        addBookmark : addBookmark
    }
}();
