function bordesNifty()
{
    AddCss();
    NiftyLoad();
    Nifty("div.footer,div.desc");
    Nifty("div.box");//,"same-height");
    Nifty("div.contenidor","bottom");
    Nifty("#submenu","top");
    Nifty("#titol_entitat","top");
    Nifty("div#dadesgenerals","bottom");
    Nifty("#login_box");
    Nifty("div.fonsverd");
    Nifty("h2.cat_title","top");
    Nifty("h2.scat_title","top");
    Nifty("ul.categoria","bottom");
    Nifty("div.poblebox","bottom");
    Nifty("div.comment");
}

function is_defined(variable)
{
    return (typeof(variable) !== "undefined");
}


function loginBoxShow() {
    if($('#login_box fieldset').hasClass('amagat')){
        $('#slogan').fadeOut('');
        $('#login_box').show('slow',function () {
            $("#login_box fieldset").removeClass('amagat');
        });
    }else{
        loginBoxHide();
    }
    return false;
}

function loginBoxHide() {
    $("#login_box fieldset").addClass('amagat');
    $('#login_box').hide('slow');
    $('#slogan').fadeIn('slow');
    
    return false;
}



$(document).ready(function(){


    $(function(){
        $('#minilogin input').keydown(function(e){
            if (e.keyCode == 13) {
                $('#minilogin').submit();
                return false;
            }
        });
    });



    $('.delete').click(function () {
        var re = new RegExp('.*\/([^\/]+)[\/]?$');
        var entnom=this.href.replace(re,'$1');
        return confirm('Are you sure to delete '+entnom+'?');
    });

    // bordes redons
    // niftycube
    bordesNifty();
    
    pngFix();
    $("#login_box fieldset").addClass('amagat');
    // login mini
    
    $("a#showLogin").click(loginBoxShow);
    $("a#hideLogin").click(loginBoxHide);
    $("#login").val(1);
    
    // galeries de fotos
    $("a[rel^='lightBox']").prettyPhoto({
        opacity: 0.80,
        allowresize: false
    });

    jQuery.validator.addMethod("userchars", function(value, element) {
        re=new RegExp("^([a-zA-Z0-9._]|-)+$");
        return this.optional(element) || re.test(value);
    }, messages.userchars);

    lang = $('#info_lang').html();
    user = $('#info_user').html();
    entitat = $('#info_entitat').html();

    window.wijwij = {
        lang: lang,
        user: user,
        entitat: entitat
    }

    // validar formularis
    $("form.validable").validate({
        rules: {
            newentityname: {
                required: true,
                remote: {
                    url: "/en/wijwij/ajax/available-entity-name/",
                    type: "post"
                }
            },
            newusername: {
                required: true,
                minlength: 4,
                maxlength: 30,
                userchars: true,
                remote: {
                    url: "/en/wijwij/ajax/available-user-name/",
                    type: "post"
                }
            },
            newemail: {
                required: true,
                email: true,
                remote: {
                    url: "/en/wijwij/ajax/available-email/",
                    type: "post"
                }
            },
            simplemail: {
                required: true,
                email: true
            },
            username: {
                required: true,
                minlength: 4,
                maxlength: 30,
                userchars: true
            },
            password: {
                required: true,
                minlength: 6,
                maxlength: 30
            }
        },
        messages: {
            newentityname: {
                remote: jQuery.format("{0} " + messages.alreadytaken)
            },
            newusername: {
                remote: jQuery.format("{0} " + messages.alreadytaken)
            },
            newemail: {
                remote: jQuery.format("{0} " + messages.alreadytaken)
            }
        }

    });
    
    $('#langselector').SelectCustomizer(addChangeLanguage);
    //$('select').SelectCustomizer();

    if(is_defined($.datepicker)) {
        $.datepicker.setDefaults($.datepicker.regional[(lang=='en')?'':lang]);
        $('#birthdate').datepicker({
            inline:true,
            changeMonth: true,
            changeYear: true,
            minDate: '-90Y',
            maxDate: '-16Y',
            yearRange: '-90,-16'
        })
        $('#birthdate').parent().append('<img id="bth_calendar" src="/imatges/mini_calendar.png" style="margin-left: 2px; vertical-align: middle;"/>');
        $('#bth_calendar').click(function(){
            $('#birthdate').focus()
            });
    }
});

function addChangeLanguage() {
    new_lang = '';
    if(typeof($("#langselector_customselect").val())!='undefined')
        new_lang = $("#langselector_customselect").val();
    else
        new_lang = $("#langselector").val();

    if( new_lang != window.wijwij.lang) {
        $('#change_lang').submit();
    }
}

function pngFix() {
    if (document.all && /MSIE (5\.5|6)/.test(navigator.userAgent) &&
        document.styleSheets && document.styleSheets[0] && document.styleSheets[0].addRule)
        {
        //document.styleSheets[0].addRule('*', 'behavior: url(/css/iepngfix.htc)');
        document.styleSheets[0].addRule('img', 'behavior: url(/css/iepngfix.htc)');
        document.styleSheets[0].addRule('div', 'behavior: url(/css/iepngfix.htc)');
        document.styleSheets[0].addRule('h1', 'behavior: url(/css/iepngfix.htc)');
        document.styleSheets[0].addRule('form', 'behavior: url(/css/iepngfix.htc)');
    // NO FUNCIONA document.styleSheets[0].addRule('input', 'behavior: url(/css/iepngfix.htc)');
    }
}

(function($){
    jQuery.expr[':'].regex = function(elem, index, match) {
        var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
            matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
        return regex.test(jQuery(elem)[attr.method](attr.property));
    }
})(jQuery);

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.cacheImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery);

// select customizer
(function($){ // hide the jquery namespace and make it compatible with other libs
    $.fn.SelectCustomizer = function(callback){
        // Select Customizer jQuery plug-in
        // based on customselect by Ace Web Design http://www.adelaidewebdesigns.com/2008/08/01/adelaide-web-designs-releases-customselect-with-icons/
        // modified by David Vian http://www.ildavid.com/dblog
        // and then modified AGAIN be Dean Collins http://www.dblog.com.au
        return this.each(function(){
            var obj = $(this);
            var name = obj.attr('id');
            var id_slc_options = name+'_options';
            var id_icn_select = name+'_iconselect';
            var id_holder = name+'_holder';
            var custom_select = name+'_customselect';
            obj.after("<div id=\""+id_slc_options+"\" class=\"optionswrapper\"> </div>");
            obj.find('option').each(function(i){
                $("#"+id_slc_options).append("<div title=\"" + $(this).attr("value") + "\" class=\"selectitems\"><span>" + $(this).html() + "</span></div>");
            });
            obj.before("<input type=\"hidden\" value =\"\" name=\"" + this.name + "\" id=\""+custom_select+"\"/><div class=\"iconselect\" id=\""+id_icn_select+"\">" + this.title + "</div><div id=\""+id_holder+"\" class=\"selectwrapper\"> </div>").remove();
            $("#"+id_icn_select).click(function(a){
                if($("#"+id_holder).css('display') == 'none') {
                    $('.selectwrapper').hide();
                    $("#"+id_holder).fadeIn(200);
                    $("#"+id_holder).focus();
                    a.stopPropagation();
                    $(document).keypress(function(e) {
                        if(!e) var e = window.event;
                        e.cancelBubble = true;
                        e.returnValue = false;
                        if (e.stopPropagation) {
                            e.stopPropagation();
                            e.preventDefault();
                        }
                    });
                    $(document).keyup(function(e) {

                        if(e.which == 40) {
                            var lastSelected = $("#"+id_holder+" .selectedclass");
                            if(lastSelected.size() == 0) {
                                var nextSelected =  $("#"+id_slc_options+" div:first:");
                            } else {
                                var nextSelected = lastSelected.next(".selectitems");
                            }
                            if(nextSelected.size() == 1) {
                                lastSelected.removeClass("selectedclass");
                                nextSelected.addClass("selectedclass");
                                $("#"+custom_select).val(nextSelected.title);
                                $("#"+id_icn_select).html(nextSelected.html());
                                var rowOffset = (nextSelected.offset().top - $("#"+id_holder).offset().top);
                                if(rowOffset > 130) {
                                    $("#"+id_slc_options).scrollTo(($("#"+id_slc_options).scrollTop() + 27) +  "px");
                                }
                            }

                        } else if(e.which == 38) {
                            var lastSelected = $("#"+id_holder+" .selectedclass");
                            var nextSelected = lastSelected.prev(".selectitems");
                            if(nextSelected.size() == 1) {
                                lastSelected.removeClass("selectedclass");
                                nextSelected.addClass("selectedclass");
                                $("#"+custom_select).val(nextSelected.title);
                                $("#"+id_icn_select).html(nextSelected.html());
                                var rowOffset = (nextSelected.offset().top - $("#"+id_holder).offset().top);
                                if(rowOffset > 0) {
                                    $("#"+id_slc_options).scrollTo(($("#"+id_slc_options).scrollTop() - 27) +  "px");
                                }
                            }
                        } else if(e.which == 13) {
                            $("#"+id_holder).fadeOut(250);
                            $(document).unbind('keyup');
                            $(document).unbind('keypress');
                            $('body').unbind('click');
                        }

                    });
                    $('body').click(function(){
                        $("#"+id_holder).fadeOut(200);
                        $('body').unbind('click');
                        $(document).unbind('keyup');
                        $(document).unbind('keypress');
                    });
                } else {
                    $("#"+id_holder).fadeOut(200);
                    $('body').unbind('click');
                    $(document).unbind('keyup');
                    $(document).unbind('keypress');
                }
            });
            $("#"+id_holder).append($("#"+id_slc_options)[0]);
            $("#"+id_holder).append("<div class=\"selectfooter\"></div>");
            $("#"+id_slc_options+" > div:last").addClass("last");
            $("#"+id_holder+ " .selectitems").mouseover(function(){
                $(this).addClass("hoverclass");
            });
            $("#"+id_holder+" .selectitems").mouseout(function(){
                $(this).removeClass("hoverclass");
            });
            $("#"+id_holder+" .selectitems").click(function(){
                $("#"+id_holder+" .selectedclass").removeClass("selectedclass");
                $(this).addClass("selectedclass");
                var thisselection = $(this).html();
                $("#"+custom_select).val(this.title);
                $("#"+id_icn_select).html(thisselection);
                $("#"+id_holder).fadeOut(250);
                $(document).unbind('keyup');
                $(document).unbind('keypress');
                $('body').unbind('click');
                if(typeof(callback)!='undefined') callback();
            });
        });
    }
})(jQuery); // pass jQuery in as the value for the $ parameter in the closure function


