/**
 * @Package: WordPress Plugin
 * @Subpackage: Ultra Portfolio
 * @Since: Ultra Portfolio 1.0
 * @Current Version: Ultra Portfolio 3.1
 * @WordPress Version: 3.5 or above
 * This file is part of Ultra Portofolio WordPress Plugin.
 */

jQuery(function ($) {
        function sortload_portfolio_items(){

            if($("#uport_sortitemsby").val() == "custom"){

                var id = $("#uport_id").val();
                var pid = $("#uport_info").attr("data-pid");
                var catids = $("#uport_categories").val();
                var woocatids = $("#uport_woocategories").val();
                var sortorder = $("#uport_sortitemslist").val();
                //console.log(catids + woocatids);

                var data = {
                    pid: pid,
                    id: id,
                    catids: catids,
                    woocatids: woocatids,
                    sortorder: sortorder,
                    action: 'uport_sort_portfolio_items',
                    uport_nonce: uport_vars.uport_nonce
                };

                $.post(ajaxurl, data, function(response) {
                    //alert(response); exit;
                    $('#uport_sortitemslist_dragdrop').html(response);

                    $( "#sortable" ).sortable({
                        placeholder: "ui-state-highlight",
                        update: function( event, ui ) {
                            //var sortedIDs = $( "#sortable" ).sortable( "serialize", { key: "sort" } );
                            var sortedIDs = $( "#sortable" ).sortable( "toArray");
                            //console.log(sortedIDs);
                            $("#uport_sortitemslist").val(sortedIDs);
                        }
                    });
                });
            }
            return false;
        }


        /*---------------------------------------------------------
         Change style in the webpage
         ---------------------------------------------------------*/


        function change_live(type) {

            var settingids = $("#uport_" + type + "values").val();
            var str = setting_values(settingids);
            var id = $("#uport_id").val();
            var pid = $("#uport_info").attr("data-pid");
            var effcss = $("#uport_info").attr("data-effcss");
            var gtype = $("#uport_info").attr("data-gtype");

            var data = {
                pid: pid,
                gtype: gtype,
                effcss: effcss,
                id: id,
                type: type,
                values: str,
                action: 'uport_load_live_preview',
                uport_nonce: uport_vars.uport_nonce
            };

            $.post(ajaxurl, data, function(response) {
                //alert(response); exit;
                $('#uport_loadit').html(response);
            });
            return false;
        }



        /*---------------------------------------------------------
         Grab step values and generate a string
         ---------------------------------------------------------*/

        function setting_values(settingids) {

            var idsspl = "";
            var str = "";
            idsspl = settingids.split("|");
            var x = idsspl.length;
            var val = "";
            var i = 0;
            for (i = 0; i < x; i++) {
                if (idsspl[i] != "") {
                    // if checkbox
                    if (($('.uport_' + idsspl[i]).is(':checkbox')) || ($('.uport_' + idsspl[i]).is(':radio')))
                    {
                        val = "";
                        $('.uport_' + idsspl[i]).each(function() {
                            if ($(this).is(":checked")) {
                                val += $(this).val() + "|";
                            }
                        });
                    }
                    // if multi select + ctrl click box
                    else if ($("#uport_" + idsspl[i]+"[multiple]").length)
                    {       
                        val = "";
                            //var foo = []; 
                            $("#uport_" + idsspl[i] + " :selected").each(function(i, selected){ 
                              //foo[i] = $(selected).text(); 
                              val += $(selected).val()+"|";
                            });


                    }            
                    // if text or select
                    else if ($("#uport_" + idsspl[i]).length)
                    {
                        val = ""; //alert(i); //alert(idsspl[i]);
                        val = document.getElementById("uport_" + idsspl[i]).value;
                        //console.log(val);
                        //alert(val);
                    }
                    str += idsspl[i] + "=" + encodeURIComponent(val);
                    if (i != (x - 1)) {
                        str += "&";
                    }
                }
            }
            //console.log(str);
            return str;
        }




        /*---------------------------------------------------------
         Grab step values and generate a string
         ---------------------------------------------------------*/

        function newLivePreview() {
            //console.log($("#uport_id").val());

            // same as reloadLivePreview in strict mode above
            var id = $("#uport_id").val();
            //alert(str);
            var data = {
                id: id,
                action: 'uport_reload_live_preview',
                uport_nonce: uport_vars.uport_nonce
            };
            $.post(ajaxurl, data, function(response) {
                //alert(response); exit;
                $('#uport_live_result').html(response);

                /*Change liveCSS style too*/
                change_live('title');
                change_live('desc');
                change_live('slug');
                change_live('but');
                change_live('buthover');
                change_live('maskbg');
                change_live('outbg');
                change_live('portbg');
                change_live('catul');
                change_live('catli');
                change_live('catlihover');
                change_live('border');
                change_live('shadow');
                change_live('price');
                change_live('above');
            });
            return false;
        }



    'use strict';

    var UPORT_SETTINGS = window.UPORT_SETTINGS || {};


    /*---------------------------------------------------------
     Main Tabs
     ---------------------------------------------------------*/
    UPORT_SETTINGS.horizontalTabs = function() {

        $(".uport_tabs .uport_tab").on('click', function(e) {
            var tabid = $(this).attr("data-tabid");
            $(".uport_tabs .uport_tab").removeClass("active");
            $(this).addClass("active");
            $(".uport_contents .uport_content").removeClass("active");
            $(".uport_contents #uport" + tabid + "_content").addClass("active");
        });




    };



    /*---------------------------------------------------------
     CSS styling inner tabs Style
     ---------------------------------------------------------*/
    UPORT_SETTINGS.cssTabsStyle = function() {

        $(".csstabs_links .csstabs").on('click', function(e) {
            var tabid = $(this).attr("id");
            $(".csstabs_links .csstabs").removeClass("active");
            $(this).addClass("active");
            $(".csstabs_data .csstabs").removeClass("active");
            $(".csstabs_data ." + tabid).addClass("active");

        });

    };



    /*---------------------------------------------------------
     Fonts
     ---------------------------------------------------------*/
    UPORT_SETTINGS.fontSettings = function() {

        $("#uport_titlefontname, #uport_descfontname, #uport_slugfontname, #uport_catfontname, #uport_butfontname, #uport_pricefontname, #uport_abovefontname").on('change', function(e) {

            var id = $(this).attr("id");
            var font = $(this).val();
            var weightid = ''; 
            var subsetid = '';

            if(id == "uport_titlefontname"){ weightid = 'uport_titlefontweight'; subsetid = 'uport_titlefontsubset'; }
            if(id == "uport_descfontname"){ weightid = 'uport_descfontweight'; subsetid = 'uport_descfontsubset'; }
            if(id == "uport_slugfontname"){ weightid = 'uport_slugfontweight'; subsetid = 'uport_slugfontsubset'; }
            if(id == "uport_catfontname"){ weightid = 'uport_catfontweight'; subsetid = 'uport_catfontsubset'; }
            if(id == "uport_butfontname"){ weightid = 'uport_butfontweight'; subsetid = 'uport_butfontsubset'; }
            if(id == "uport_pricefontname"){ weightid = 'uport_pricefontweight'; subsetid = 'uport_pricefontsubset'; }
            if(id == "uport_abovefontname"){ weightid = 'uport_abovefontweight'; subsetid = 'uport_abovefontsubset'; }


            var action = 'uport_load_font';
            var data = {
                id: id,
                font: font,
                action: action,
                uport_nonce: uport_vars.uport_nonce
            };

        $.post(ajaxurl, data, function(response) {
            var split = response.split('|||');
            $('#'+weightid).html(split[0]);
            $('#'+subsetid).html(split[1]);
            $('#'+weightid).parent().find(".custom-combobox-input").val("");
            $('#'+subsetid).parent().find(".custom-combobox-input").val("");
        });

        return false;

        });

    };



    /*---------------------------------------------------------
     Color Picker
     ---------------------------------------------------------*/
    UPORT_SETTINGS.colorPicker = function() {
        var myOptions = {
            change: function(event, ui) {
                //console.log($(this).val());
                //$('.my-color-field').change();
            },
            clear: function() {
            },
            hide: true,
            palettes: true
        };
        $('.my-color-field').wpColorPicker(myOptions);
    };

    /*---------------------------------------------------------
     Ajax Save a Step
     ---------------------------------------------------------*/
    UPORT_SETTINGS.pickEffect = function() {
        $(".uport_effect").on('click', function(e) {
            var effect = $(this).attr("data-effect");
            $(".uport_effect_sublist").hide();
            $(".uport_effect_sublist_" + effect).show();
            $("input[data-parent-effect='" + effect + "'][value='default']").attr('checked', 'checked');

        });

    };

    UPORT_SETTINGS.pickElement = function() {
        $(".uport_element").on('click', function(e) {
            var element = $(this).attr("data-element");

            if ($(this).is(":checked")) {
                $(".uport_element_sublist_" + element).show();
            } else {
                $(".uport_element_sublist_" + element).hide();
            }

            $("input[data-parent-element='" + element + "'][value='default']").attr('checked', 'checked');

        });

        $(".uport_subelement").on('click', function(e) {
            var textid = $(this).attr("data-textid");
            var textval = $("#" + textid).val();
            var parent = $(this).attr("data-parent-element");
            var thisval = parent + "_" + $(this).val();

            var textval = textval.replace(parent + "_", "");
            var textval = textval.replace("|out|", "|");
            var textval = textval.replace("|over|", "|");
            var textval = textval.replace("|above|", "|");
            var textval = textval.replace("|tagline|", "|");
            var textval = textval.replace("|date|", "|");
            var textval = textval.replace("||", "|");


            //$("#"+textid).val(newtextval);

            if ($(this).is(":checked")) {
                $("#" + textid).val("|" + thisval + "|" + textval);
            } else {
            }
        });



    };




    /*---------------------------------------------------------
     Ajax Save a Step
     ---------------------------------------------------------*/
    UPORT_SETTINGS.ajaxSave = function() {

        $("#uport_submitstep1").on('click', function(e) {
            ajaxsavestep(1);
            return false;
        });
        $("#uport_submitstep2").on('click', function(e) {
            ajaxsavestep(2);
            return false;
        });
        $("#uport_submitstep3").on('click', function(e) {
            ajaxsavestep(3);
            return false;
        });
        $("#uport_submitstep4").on('click', function(e) {
            ajaxsavestep(4);
            return false;
        });
        $(".uport_submitstepall").on('click', function(e) {
            ajaxsavestepall();
            return false;
        });

    };

    function ajaxsavestepall() {
        var stepid = 'all';
        //$(".uport_savetxt").html("").hide();
        //$("#uport_save_step"+stepid+"_result").show();
        $(".uport_submitstepall").addClass("saving");
        //$("#uport_save_step"+stepid+"_result").html("<span class='loadingtext'>Saving All Sections...</span>");

        var id = $("#uport_id").val();
        var settingids1 = $("#uport_settingids_1").val();        //alert(settingids1);
        var settingids2 = $("#uport_settingids_2").val();        //alert(settingids2);
        var settingids3 = $("#uport_settingids_3").val();        //alert(settingids3);
        var settingids4 = $("#uport_settingids_4").val();        //alert(settingids4);

        var str1 = setting_values(settingids1);
        var str2 = setting_values(settingids2);
        var str3 = setting_values(settingids3);
        var str4 = setting_values(settingids4);

        var action = 'uport_load_step' + stepid;

        var data = {
            id: id,
            values1: str1,
            values2: str2,
            values3: str3,
            values4: str4,
            action: action,
            uport_nonce: uport_vars.uport_nonce
        };

        $.post(ajaxurl, data, function(response) {
            $('#uport_save_step' + stepid + '_result').html(response);
            var myOptions = {
                change: function(event, ui) {
                },
                clear: function() {
                },
                hide: true,
                palettes: true
            };
            $('.my-color-field').wpColorPicker(myOptions);

            /*---------------------------------------------------------
             Reload Live Preview on saving a step
             ---------------------------------------------------------*/
            if (id != "") {
                UPORT_SETTINGS.reloadLivePreview();
            }

            $(".uport_submitstepall").removeClass("saving");
            $(".uport_save_msg").addClass("saved").html("Saved all sections").fadeOut(3000);

        });

        return false;




    }


    function ajaxsavestep(stepid) {
        //$(".uport_savetxt").html("").hide();
        //$("#uport_save_step"+stepid+"_result").show();
        //$("#uport_save_step"+stepid+"_result").html("<span class='loadingtext'>Saving section...</span>");

        $("#uport_submitstep" + stepid).addClass("saving");

        var id = $("#uport_id").val();
        var settingids = $("#uport_settingids_" + stepid + "").val();        //alert(settingids);
        var str = setting_values(settingids);
        //alert(str); exit;
        var action = 'uport_load_step' + stepid;
        var data = {
            id: id,
            values: str,
            action: action,
            uport_nonce: uport_vars.uport_nonce
        };

        $.post(ajaxurl, data, function(response) {
            //alert(response);
            $('#uport_save_step' + stepid + '_result').html(response);
            var myOptions = {
                change: function(event, ui) {
                },
                clear: function() {
                },
                hide: true,
                palettes: true
            };
            $('.my-color-field').wpColorPicker(myOptions);

            /*---------------------------------------------------------
             Reload Live Preview on saving a step
             ---------------------------------------------------------*/
            if (stepid == 1 || stepid == 2 || stepid == 3 || stepid == 4) {
                if (id != "") {
                    UPORT_SETTINGS.reloadLivePreview();
                }
            }

            $("#uport_submitstep" + stepid).removeClass("saving");
            $(".uport_save_msg_step"+stepid).addClass("saved").html("Saved section").fadeOut(3000);

        });

        return false;
    }


    /*---------------------------------------------------------
     Reload Live Preview on saving a step
     ---------------------------------------------------------*/

    UPORT_SETTINGS.reloadLivePreview = function() {
        newLivePreview();
        return false;
    };


    /*---------------------------------------------------------
     CSS Style of Live Preview on changing
     ---------------------------------------------------------*/
    UPORT_SETTINGS.liveCSS = function() {

        $(".wp-picker-container").on('click', function(e) {
            var field = $(this).parent().find(".my-color-field");
            var color = field.val();
            var oftype = field.attr("data-oftype");
            field.val(color);
            //console.log(oftype + ": " + color);

            if (oftype == "livetitle") {
                change_live('title');
            }
            if (oftype == "livedesc") {
                change_live('desc');
            }
            if (oftype == "liveslug") {
                change_live('slug');
            }
            if (oftype == "livebut") {
                change_live('but');
            }
            if (oftype == "livebuthover") {
                change_live('buthover');
            }
            if (oftype == "livemaskbg") {
                change_live('maskbg');
            }
            if (oftype == "liveoutbg") {
                change_live('outbg');
            }
            if (oftype == "liveportbg") {
                change_live('portbg');
            }
            if (oftype == "livecatul") {
                change_live('catul');
            }
            if (oftype == "livecatli") {
                change_live('catli');
            }
            if (oftype == "livecatlihover") {
                change_live('catlihover');
            }
            if (oftype == "liveborder") {
                change_live('border');
            }
            if (oftype == "liveshadow") {
                change_live('shadow');
            }
            if (oftype == "liveprice") {
                change_live('price');
            }
            if (oftype == "liveabove") {
                change_live('above');
            }

            return false;
        });

        $('.livetitle').on('change', function(e) {
            change_live('title');
            return false;
        });
        $('.livedesc').on('change', function(e) {
            change_live('desc');
            return false;
        });
        $('.liveslug').on('change', function(e) {
            change_live('slug');
            return false;
        });
        $('.livebut').on('change', function(e) {
            change_live('but');
            return false;
        });
        $('.livebuthover').on('change', function(e) {
            change_live('buthover');
            return false;
        });
        $('.livemaskbg').on('change', function(e) {
            change_live('maskbg');
            return false;
        });
        $('.liveoutbg').on('change', function(e) {
            change_live('outbg');
            return false;
        });
        $('.liveportbg').on('change', function(e) {
            change_live('portbg');
            return false;
        });
        $('.livecatul').on('change', function(e) {
            change_live('catul');
            return false;
        });
        $('.livecatli').on('change', function(e) {
            change_live('catli');
            return false;
        });
        $('.livecatlihover').on('change', function(e) {
            change_live('catlihover');
            return false;
        });
        $('.liveborder').on('change', function(e) {
            change_live('border');
            return false;
        });
        $('.liveshadow').on('change', function(e) {
            change_live('shadow');
            return false;
        });
        $('.liveprice').on('change', function(e) {
            change_live('price');
            return false;
        });
        $('.liveabove').on('change', function(e) {
            change_live('above');
            return false;
        });

    };


    /*---------------------------------------------------------
     CSS Style of Live Preview on changing
     ---------------------------------------------------------*/
    UPORT_SETTINGS.changeMessage = function() {

        $('.uport_1_field').on('change', function(e) {
            $(".uport_save_msg_step1").removeClass("saved").html("Section settings changed. Save it.").fadeIn(1000);
            return false;
        });
        $('.uport_2_field').on('change', function(e) {
            $(".uport_save_msg_step2").removeClass("saved").html("Section settings changed. Save it.").fadeIn(1000);
            return false;
        });
        $('.uport_3_field').on('change', function(e) {
            $(".uport_save_msg_step3").removeClass("saved").html("Section settings changed. Save it.").fadeIn(1000);
            return false;
        });
        $('.uport_4_field').on('change', function(e) {
            $(".uport_save_msg_step4").removeClass("saved").html("Section settings changed. Save it.").fadeIn(1000);
            return false;
        });

    };



    /*---------------------------------------------------------
     Dependency
     ---------------------------------------------------------*/
    UPORT_SETTINGS.manageDependency = function() {

        $(".has_dependent").on('change', function(e) {
            var id = $(this).attr("data-fieldid");
            var val = $(this).attr("value");
            dependent_condition(id,val);
        });

        $(".has_dependent").each(function(){
                    var id = $(this).attr("data-fieldid");
                    var val = $(this).attr("value");
                    dependent_condition(id,val);
          });


    };


        function dependent_condition(id,val){
            //console.log(id+":"+val);

            var selector = ".is_dependent.dependent_on_"+id;
            var check_class = id+"_"+val;

            $(selector).hide();
            if($(selector).hasClass(check_class)){
                $(selector+"."+check_class).show();
            }

        }




    /*---------------------------------------------------------
     Custom Sorting - added in version 1.2
     ---------------------------------------------------------*/
    UPORT_SETTINGS.customSorting = function() {

        $("#uport_sortitemsby").on('change', function(e) {
            if($(this).val() == "custom"){
                $("#uport_sortitemslist_dragdrop").show();
                sortload_portfolio_items();
            } else {
                $("#uport_sortitemslist_dragdrop").hide();
            }
        });

    };



    /*---------------------------------------------------------
     Table listing checkbox select
     ---------------------------------------------------------*/

    UPORT_SETTINGS.rowSelectBox = function() {

     $(document).on( 'click', '.uportallrow', function (){
        if ($(this).is(":checked")) {
            //console.log("select all");
            $(".uportrow").prop( "checked", true );
            $(".uport_selactions").prop( "disabled", false );
        } else {
            //console.log("unselect all");
            $(".uportrow").prop( "checked", false );
            $(".uport_selactions").prop( "disabled", true );
        }
     });

     $(document).on( 'click', '.uportrow', function (){
               
            var checkcount = 0;
            $('.uportrow').each(function() {
                if ($(this).is(":checked")) {
                    checkcount = checkcount + 1
                }
            });
            var len = $('.uportrow').length;
            //console.log(len); console.log(checkcount);
            if(len == checkcount){
                $(".uportallrow").prop( "checked", true );
            } else{
                $(".uportallrow").prop( "checked", false );
            }

            if(checkcount > 0){
                $(".uport_selactions").prop( "disabled", false );
            } else {
                $(".uport_selactions").prop( "disabled", true );
            }

     });


     $(document).on( 'click', '.uport_selactions', function (){
        var actiontype = $(this).attr("data-action");
        var type = $(this).attr("data-type");
        var selids = "";
        $('.uportrow').each(function() {
                if ($(this).is(":checked")) {
                    var id = $(this).attr("data-id");
                    selids = selids + id + ",";
                }
        });
        console.log(actiontype+" "+type+" "+selids);


                var data = {
                    ids: selids,
                    actiontype: actiontype,
                    type: type,
                    action: 'uport_bulk_selactions',
                    uport_nonce: uport_vars.uport_nonce
                };
                jQuery.post(ajaxurl, data, function(response) {
                    jQuery(".uport_msg").fadeIn().html(response);

                    setTimeout(function() {
                        location.reload();
                    },
                            1000);

                    //alert(response); exit;
                    //$('#uport_live_result').html(response);
                    //window.location = url;

                });
         
            return false;





     });

    };

    /*-----------------------------------------------
     initialize respective scripts 
     ------------------------------------------------*/
    $(document).ready(function() {
        UPORT_SETTINGS.rowSelectBox();
        UPORT_SETTINGS.colorPicker();
        UPORT_SETTINGS.liveCSS();
        UPORT_SETTINGS.horizontalTabs();
        UPORT_SETTINGS.cssTabsStyle();
        UPORT_SETTINGS.ajaxSave();
        UPORT_SETTINGS.changeMessage();
        UPORT_SETTINGS.pickEffect();
        UPORT_SETTINGS.pickElement();
        UPORT_SETTINGS.fontSettings();
        UPORT_SETTINGS.manageDependency();
        UPORT_SETTINGS.customSorting();
        sortload_portfolio_items();
    });

    $(window).resize(function() {
        
    });

    $(window).load(function() {
    });









});




/*---------------------------------------------------------
 UI scripts
 ---------------------------------------------------------*/

jQuery(function($) {
    var icons = {
            header: "ui-icon-circle-arrow-e",
            activeHeader: "ui-icon-circle-arrow-s"
        };
        $( ".uport-accordion" )
            .accordion({
                
                header: "> div > h4"
            })
            .sortable({
                axis: "y",
                handle: "h4",
                stop: function( event, ui ) {
                    // IE doesn't register the blur when sorting
                    // so trigger focusout handlers to remove .ui-state-focus
                    ui.item.children( "h3" ).triggerHandler( "focusout" );
                }
            });
    });





jQuery(function($) {
    var spinner = $(".uport-spinner").spinner({
        change: function() {
            $(this).change();
        },
    });

    var spinner = $(".uport-spinner-opacity").spinner({
        step: 0.10,
        spin: function(event, ui) {
            if (ui.value > 1) {
                $(this).spinner("value", 0.10);
                return false;
            }
        },
        change: function() {
            $(this).change();
        },
    });
   
});





jQuery(function($) {
    //(function( $ ) {
    $.widget("custom.combobox", {
        _create: function() {
            this.wrapper = $("<span>")
                    .addClass("custom-combobox")
                    .insertAfter(this.element);

            this.element.hide();
            this._createAutocomplete();
            this._createShowAllButton();
        },
        _createAutocomplete: function() {
            var selected = this.element.children(":selected"),
                    value = selected.val() ? selected.text() : "";

            this.input = $("<input>")
                    .appendTo(this.wrapper)
                    .val(value)
                    .attr("title", "")
                    .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
                    .autocomplete({
                        delay: 0,
                        minLength: 0,
                        source: $.proxy(this, "_source")
                    })
                    .tooltip({
                        tooltipClass: "ui-state-highlight"
                    });

            this._on(this.input, {
                autocompleteselect: function(event, ui) {
                    ui.item.option.selected = true;
                    this._trigger("select", event, {
                        item: ui.item.option
                    });
                },
                autocompletechange: "_removeIfInvalid"
            });
        },
        _createShowAllButton: function() {
            var input = this.input,
                    wasOpen = false;

            $("<a>")
                    .attr("tabIndex", -1)
                    .attr("title", "")
                    .tooltip()
                    .appendTo(this.wrapper)
                    .button({
                        icons: {
                            primary: "ui-icon-triangle-1-s"
                        },
                        text: false
                    })
                    .removeClass("ui-corner-all")
                    .addClass("custom-combobox-toggle ui-corner-right")
                    .mousedown(function() {
                        wasOpen = input.autocomplete("widget").is(":visible");
                    })
                    .click(function() {
                        input.focus();

                        // Close if already visible
                        if (wasOpen) {
                            return;
                        }

                        // Pass empty string as value to search for, displaying all results
                        input.autocomplete("search", "");
                    });
        },
        _source: function(request, response) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
            response(this.element.children("option").map(function() {
                var text = $(this).text();
                if (this.value && (!request.term || matcher.test(text)))
                    return {
                        label: text,
                        value: text,
                        option: this
                    };
            }));
        },
        _removeIfInvalid: function(event, ui) {

            // Selected an item, nothing to do
            if (ui.item) {
                return;
            }

            // Search for a match (case-insensitive)
            var value = this.input.val(),
                    valueLowerCase = value.toLowerCase(),
                    valid = false;
            this.element.children("option").each(function() {
                if ($(this).text().toLowerCase() === valueLowerCase) {
                    this.selected = valid = true;
                    return false;
                }
            });

            // Found a match, nothing to do
            if (valid) {
                return;
            }

            // Remove invalid value
            this.input
                    .val("")
                    .attr("title", value + " didn't match any item")
                    .tooltip("open");
            this.element.val("");
            this._delay(function() {
                this.input.tooltip("close").attr("title", "");
            }, 2500);
            this.input.data("ui-autocomplete").term = "";
        },
        _destroy: function() {
            this.wrapper.remove();
            this.element.show();
        }
    });
    //})( jQuery );
});


jQuery(function($) {
    $(".uport-combobox").combobox({
        select: function(event, ui) {
            $(this).change();
            //alert(this.parent().parent().find("select").attr("id"));
        }
    });
});

jQuery(function($) {
    $(".uport-combobox-multi").combobox({
        select: function(event, ui) {
            $(this).change();

            /*var output = '';
            for (var property in ui.item) {
              output += property + ': ' + ui.item[property]+'; ';
            }*/

            var field = $(this).parent().parent().find("select").attr("data-id");
            var newid = $(this).val();
            var val = $("."+field).attr("value");
            var tags = $("."+field+"_tags").html();

            //console.log(newid + ui.item.text + field);
            if(newid != "0"){
                if (val.indexOf("|"+newid+"|") < 0){
                    
                    var newval = val+"|"+newid+"|";
                    $("."+field).attr("value",newval);

                    var newtags = tags+"<span class='multiselectval' data-field='"+field+"' id='"+newid+"'>"+ui.item.text+"<span>x</span></span>";
                    $("."+field+"_tags").html(newtags);

                    if(field == "uport_categories" || field == "uport_woocategories"){
                        // call a jquery ajax function to load items from portfolio categories
                        sortload_portfolio_items();
                    }
                }
            }
        }
    });



     $(document).on( 'click', '.multiselectval span', function (){
     //$(".multiselectval span").on('click', function(e) {
            //alert("hi");
            var field = $(this).parent().attr("data-field");
            var id = $(this).parent().attr("id");

            $(this).parent().remove();

            var inputval = $("."+field).attr("value");
            inputval = inputval.replace("|"+id + "|", "|");
            inputval = inputval.replace("||", "|");
            $("."+field).attr("value",inputval);

            if(field == "uport_categories" || field == "uport_woocategories"){
                // call a jquery ajax function to load items from portfolio categories
                sortload_portfolio_items();
            }

        });



});



//jQuery(function($) {
/*---------------------------------------------------------
 Delete category and item function
 ---------------------------------------------------------*/
function uport_delthis(url, type, id)
{
    var msg = "";
    if (type == 'del_portfolio') {
        msg = "Are you sure, you want to delete portfolio: " + id;
    }
    if (type == 'del_item') {
        msg = "Are you sure, you want to delete Item: " + id;
    }
    if (type == 'del_category') {
        msg = "Are you sure, you want to delete Category: " + id;
    }
    a = confirm(msg);
    if (a) {
        return true;
    }
}



function uport_actionthis(url, id, type) {

    var action = 'uport_copythis';
    var confirm = true;
    
    if (type == "del_item" || type == 'del_portfolio' || type == 'del_category') {
        action = 'uport_deletethis';
        confirm = uport_delthis(url, type, id);
    }

    if (confirm) {
        var data = {
            id: id,
            url: url,
            type: type,
            action: action,
            uport_nonce: uport_vars.uport_nonce
        };
        jQuery.post(ajaxurl, data, function(response) {
            jQuery(".uport_msg").fadeIn().html(response);

            setTimeout(function() {
                window.location = url;
            },
                    1000);

            //alert(response); exit;
            //$('#uport_live_result').html(response);
            //window.location = url;

        });
    }
    return false;
}
//});





