if (typeof POLAR == 'undefined' || !POLAR) {
    var POLAR = {};
}
//------------------------------------------------------------------
//Attach function GetPropertyName to sended objectX
//example of use this attaced function is:
//      var item = resource.Items[0];
//      POLAR.View.SetPropertyNameToObject(item);
POLAR.View.SetPropertyNameToObject = function(objectX) {

    var getPropertyNameByObject = function(strPropertyName, resourceObject) {    
        var splittedSubstrings = strPropertyName.split(".");
        try {
            if (splittedSubstrings.length == 1) {
                if (resourceObject[strPropertyName] !== undefined) {
                    return strPropertyName;
                }
            }
            if (splittedSubstrings.length == 2) {
                var objectA = resourceObject[splittedSubstrings[0]];
                if (objectA !== undefined) {
                    if (objectA[splittedSubstrings[1]] !== undefined) {
                        return strPropertyName;
                    }
                }
            }
            if (splittedSubstrings.length == 3) {
                var objectA = resourceObject[splittedSubstrings[0]];
                if (objectA !== undefined) {
                    var objectB = objectA[splittedSubstrings[1]];
                    if (objectB[splittedSubstrings[2]] !== undefined) {
                        return strPropertyName;
                    }
                }
            }
        }
        catch (e) {
        }
        $('#messagebox').text("ERROR: Property name: '" + strPropertyName + "' don not exist in resoruce representation.");
        $("#messagebox").show();
        return "";
    }   
    
    objectX.GetPropertyName = function (strPropertyName) {
        return getPropertyNameByObject(strPropertyName, objectX);
    };
}
//------------------------------------------------------------------
//Inicialize all object of POLAR.View and JSON Resopruce Representation
POLAR.View.Initialization = function() {
    //za poslati preprty vraca ime ako takava property postoji u resoruce a ako ne onda u #message ispisuje upozorenje da ne postoji i vraca prazan string.
    //Example of use -->> var strPropertyName = resource.GetPropertyName("AuthenticatedPerson.ID");
    POLAR.View.SetPropertyNameToObject(resource);        
};
//------------------------------------------------------------------
/* This function parses ampersand-separated name=value argument pairs from the query string of the URL. It stores the name=value pairs in
    properties of an object and returns that object. */
POLAR.View.getUrlArgs = function() {
    var args = new Object();
    var query = location.search.substring(1);
    var pairs = query.split('&');

    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');

        if (pos == -1) {
            continue;
        }

        var argname = pairs[i].substring(0,pos);
        argname = argname.toLowerCase();

        var value = pairs[i].substring(pos + 1);
        value = decodeURIComponent(value);
        //value = value.toLowerCase();
        args[argname] = value;
    }

    return args;
};
//-----------------------------------------------------
POLAR.View.getUrlWithoutArgs = function() {
    if (location.href.indexOf('?') > 0) {
        return location.href.substring(0, location.href.indexOf('?'));
    }
    else {
        return location.href;
    }
};
//-----------------------------------------------------
//get desktop URI e.g. "incidents" or "incidents/team/2"
POLAR.View.getDektopURI = function() {
    var uriDesktop = location.href;
    //get URL without ?
    var index1 = uriDesktop.indexOf('?');
    if (index1 != -1) {
        uriDesktop = uriDesktop.substring(0, index1);
    }
    //cut base URL
    //var index1 = uriDesktop.indexOf(BASE_URL);
    uriDesktop = uriDesktop.substring(BASE_URL.length);
    return uriDesktop; 
};
//-----------------------------------------------------
/**
* Gets URL arguments and returns it as object caintaining URL parametars as arrays of values split by ; delimiter
* e.g. &parametar1=1;2;test&parametar2=1 => args['parametar1'] = [1,2,'test'] , args['parametar2'] = 1
*/
POLAR.View.getUrlArgsParsed = function() {
    var args = POLAR.View.getUrlArgs();
    for (var key in args) {
        if (args[key].search(';') != -1) {
            var values = args[key].split(';');
            args[key] = values;
        } else {
            var tempValue = args[key];
            args[key] = [];
            args[key].push(tempValue);
        }
    }

    return args;
}
//-----------------------------------------------------
POLAR.View.Filter = function(rootEle, conf) {
    this._conf = conf;

    this._textSearchEle = POLAR.View.getElementByClassName('ps-filter-textsearch', rootEle);
    this._filterNameEle = POLAR.View.getElementByClassName('ps-filter-filtername', rootEle);
    this._publicCheckboxEle = POLAR.View.getElementByClassName('ps-filter-publiccheckbox', rootEle);
    this._viewsEle = POLAR.View.getElementByClassName('ps-filter-views', rootEle);

    var advancedViewEle = $(".ps-filter-advancedview");
    if (advancedViewEle.length > 0) {
        $(".ps-filter-showadvancedview").click(function(event) {
            event.preventDefault();
            if (advancedViewEle.is(":hidden")) {
                advancedViewEle.show("fast");
                //advancedViewEle.show();
                $('input[title!=""]').jqpHint();
                $("select.styled").jqTransform();
            } else {
                advancedViewEle.hide("fast");
            }
        });
        //advancedViewEle.hide("fast");
    }

    _this = this;

    if ($('#buttonGo').length) {
        var oGoButton = new YAHOO.widget.Button("buttonGo");
        oGoButton.on("click", function() {
            _this.callUrl();
        });
    }

    var goButtonEle = POLAR.View.getElementByClassName('ps-filter-gobutton', rootEle);
    $(this._textSearchEle).keypress(function(e) {
        if (e.which == 13) {
            _this.callUrl();
        }
    });

    if ($('#saveViewButton').length) {
        var oGoButton = new YAHOO.widget.Button("saveViewButton");
        oGoButton.on("click", function() {
            _this.save();
        });
    }

    if (undefined != this._viewsEle || null != this._viewsEle) {
        YAHOO.util.Event.addListener(this._viewsEle, 'change', function() {
            var viewsEle = _this._viewsEle;
            document.location = BASE_URL + viewsEle.options[viewsEle.selectedIndex].value;
        });
    }

    this.load();
};
//-----------------------------------------------------
POLAR.View.Filter.prototype = {
    load: function() {
        var args = POLAR.View.getUrlArgsParsed();
        for (var key in this._conf.args) {
            var value = this._conf.args[key];

            this.setControlValue(value.id, args[value.urlValueName], value.type);
        }

        if (undefined != this._conf.onSetArguments)
            this._conf.onSetArguments(args);
    },

    save: function() {
        var filterName = this._filterNameEle.value;
        if (filterName == null || filterName == '' || filterName == undefined)
            return;

        var data =
        {
            Name: filterName,
            Value: this.generateUrl(),
            Public: this._publicCheckboxEle.checked
        };

        var _this = this;
        POLAR.View.asyncPost(this._conf.viewUrl, data, function(predefinedView) {
            POLAR.View.AddDataToMessageBoxData(resource.LabelsCommon.OperationSuccess);
            if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
                _this._viewsEle.add(new Option(predefinedView.Name, predefinedView.Value));
            }
            else {
                _this._viewsEle.add(new Option(predefinedView.Name, predefinedView.Value), null);
            }

            _this._filterNameEle.value = '';
        });
    },

    removeCustomView: function() {
        for (var index = 0; index < this._viewsEle.options.length; index++) {
            if ('0' == this._viewsEle.options[index].value) {
                this._viewsEle.remove(index)
            }
        }
    },

    setControlValue: function(id, value, type) {
        var ele = YAHOO.util.Dom.get(id);
        if (YAHOO.lang.isNull(ele))
            return;

        switch (type) {
            case 'textbox':
                if (value != undefined)
                    ele.value = value;

                break;

            case 'textboxnum':
                if (value != undefined && !YAHOO.lang.isNull(Number(value)))
                    ele.value = value;

                break;

            case 'select':
                if (value != undefined) {
                    for (index = 0; index < ele.options.length; index++) {
                        var text = ele.options[index].text.toLowerCase();
                        if (text == value)
                            ele.selectedIndex = index;
                    }
                }

                break;

            case 'selectByValue':
                if (value != undefined) {
                    for (index = 0; index < ele.options.length; index++) {
                        var text = ele.options[index].value.toLowerCase();
                        if (text == value)
                            ele.selectedIndex = index;
                    }
                }

                break;

            case 'checkbox':
                if (value != undefined && YAHOO.lang.isBoolean(Boolean(value)))
                    ele.checked = Boolean(value);

                break;
        }
    },

    getControlValue: function(id, type) {
        var ele = YAHOO.util.Dom.get(id);
        if (YAHOO.lang.isNull(ele))
            return;

        switch (type) {
            case 'textbox':
            case 'textboxnum':
                return ele.value;

            case 'select':
                return ele.options[ele.selectedIndex].text.toLowerCase();

            case 'selectByValue':
                return ele.options[ele.selectedIndex].value.toLowerCase();

            case 'checkbox':
                return ele.checked;
        }
    },

    generateUrl: function() {
        var args = POLAR.View.getUrlArgsParsed();
        for (var n = 0; n < this._conf.args.length; n++) {
            var value = this._conf.args[n];
            args[value.urlValueName] = this.getControlValue(value.id, value.type);
        }

        if (undefined != this._conf.onSetArguments) {
            this._conf.onGetArguments(args);
        }

        var query = '';
        for (var key in args) {
            var value = args[key];

            if ($.isArray(value) && value.length > 0) {
                var arrayValues = '';
                for (var i = 0; i < value.length; i++) {
                    arrayValues += value[i] + ';';
                }
                // trim ';' at the end
                arrayValues = arrayValues.substring(0, arrayValues.length - 1);
                query += key + '=' + arrayValues + '&';
            } else if (!$.isArray(value) && value != undefined && value != '') {
                query += key + '=' + value + '&';
            }
        }

        return POLAR.View.getUrlWithoutArgs() + '?' + query;
    },

    callUrl: function() {
        var query = this.generateUrl();
        // remove '&' if on last position
        if ('&' == query.charAt(query.length - 1)) {
            query = query.substring(0, query.length - 1);
        }
        window.location = query;
    }
};
//-----------------------------------------------------
/*Response on load form. Fill control form ULR query value */
POLAR.View.OnLoadFillControlFromUrlQuery = function(controlAndQuery )
{
    var queryArguments = POLAR.View.getQueryArguments();
    for (var n = 0; n < controlAndQuery.entities.length; n++) {
        if(controlAndQuery.entities[n].control == 'textbox') {
            POLAR.View.updateTextBoxHelper(controlAndQuery.entities[n].id, queryArguments, controlAndQuery.entities[n].queryVariable );
        }
        if(controlAndQuery.entities[n].control == 'textboxnum') {
            POLAR.View.updateTextBoxNumHelper(controlAndQuery.entities[n].id, queryArguments, controlAndQuery.entities[n].queryVariable );
        }
        if(controlAndQuery.entities[n].control == 'select') {
            POLAR.View.updateFilterHelper(controlAndQuery.entities[n].id, queryArguments, controlAndQuery.entities[n].queryVariable );
        }
        if(controlAndQuery.entities[n].control == 'checkbox') {
            POLAR.View.updateCheckboxHelper(controlAndQuery.entities[n].id, queryArguments, controlAndQuery.entities[n].queryVariable );
        }
    }

    return queryArguments;
};
//-----------------------------------------------------
POLAR.View.updateTextBoxHelper = function (controlID, queryArguments, queryVariable)
{
    var element = document.getElementById(controlID);

    // check if supplied element ID is valid, if not do nothing
    if (element == null) {
        return;
    }

    if(queryArguments[queryVariable] != undefined) {
	    element.value = queryArguments[queryVariable];
    }
    else {
        element.value = '';
    }
};
//-----------------------------------------------------
POLAR.View.updateTextBoxNumHelper = function (controlID, queryArguments, queryVariable)
{
    if(queryArguments[queryVariable] != undefined)
    {
        var result = Number(queryArguments[queryVariable]);
	    if(isNaN(result) == false) {
	        document.getElementById(controlID).value = queryArguments[queryVariable];
	        return;
	    }			    
    }

    document.getElementById(controlID).value = '';    
};
//-----------------------------------------------------
POLAR.View.updateFilterHelper = function (controlID, queryArguments, queryVariable )
{
    var domElement = document.getElementById(controlID);
    if(domElement != null && queryArguments[queryVariable] != '')
    {
	    for(i=0; i < domElement.options.length; i++)
	    {
	        var text  = domElement.options[i].text.toLowerCase();
	        if(text == queryArguments[queryVariable])
	        {
	            domElement.selectedIndex = i;
	        }
	    }
	}
};
//-----------------------------------------------------
POLAR.View.updateCheckboxHelper = function (controlID, queryArguments, queryVariable )
{
    var domElement = document.getElementById(controlID);
    if(domElement != null)
    {
        if(queryArguments[queryVariable] == undefined)
        {
            document.getElementById(controlID).checked = false;
        }
        else if(queryArguments[queryVariable] == '')
        {
            document.getElementById(controlID).checked = false;
        }
        else
        {
            document.getElementById(controlID).checked = queryArguments[queryVariable];
        }
	}
};
//-----------------------------------------------------
POLAR.View.UrlWithoutQueryParameters = function ()
{
    if (location.href.indexOf('?') > 0) {
        return location.href.substring(0, location.href.indexOf('?'));
    }
    else {
        return location.href;
    }
}
//-----------------------------------------------------
/*Response on Go button click event */
POLAR.View.CreateUrlAndCallUrl = function(controlAndQuery)
{
    var desktopUrl = POLAR.View.UrlWithoutQueryParameters();
    //var = 'incidents';
    var queryArguments = POLAR.View.getQueryArguments();
    for (var n = 0; n < controlAndQuery.entities.length; n++) {
        if (controlAndQuery.entities[n].control == 'textbox') {
            POLAR.View.getQueryValueFromTextBox(controlAndQuery.entities[n].id, queryArguments, controlAndQuery.entities[n].queryVariable);
        }
        if (controlAndQuery.entities[n].control == 'textboxnum') {
            POLAR.View.getQueryValueFromTextBoxNum(controlAndQuery.entities[n].id, queryArguments, controlAndQuery.entities[n].queryVariable);
        }
        if (controlAndQuery.entities[n].control == 'select') {
            POLAR.View.getQueryValueFromComoBox(controlAndQuery.entities[n].id, queryArguments, controlAndQuery.entities[n].queryVariable);
        }
        if (controlAndQuery.entities[n].control == 'checkbox') {
            POLAR.View.getQueryValueFromCheckBox(controlAndQuery.entities[n].id, queryArguments, controlAndQuery.entities[n].queryVariable);
        }
    }

    /*Construct new URL*/
    var query = '';
    for (argname in queryArguments) {
        if (queryArguments[argname] != '') {
            query = query + argname + '=' + queryArguments[argname] + '&';
        }
    }
    query = query.substr(0, query.length - 1);
    if (query != '') {
        window.location = desktopUrl + '?' + query;
    }
    else {
        window.location = desktopUrl;
    }
};
//-----------------------------------------------------
/*Fill queryArguments with data from control preparing it for creating from array new URL*/
POLAR.View.getQueryValueFromTextBox =  function(controlID, queryArguments, queryVariable)
{
    var domElement = document.getElementById(controlID);
     if((domElement != null)  )
	{
	    queryArguments[queryVariable] = domElement.value;
	}
	else
	{
	    queryArguments[queryVariable] = '';
	}
};
//-----------------------------------------------------
/*Fill queryArguments with data from control preparing it for creating from array new URL*/
POLAR.View.getQueryValueFromTextBoxNum =  function(controlID, queryArguments, queryVariable)
{
    var domElement = document.getElementById(controlID);
     if((domElement != null)  )
	{
	    var result = Number(domElement.value);
	    if(isNaN(result) == false)
	    {
	        queryArguments[queryVariable] = domElement.value;  
	    }
	    else
	    {
		    queryArguments[queryVariable] = '';
	    }
	}
	else
	{
	    queryArguments[queryVariable] = '';
	}
};

/*Fill queryArguments with data from control preparing it for creating from array new URL*/
POLAR.View.getQueryValueFromComoBox =  function(controlID, queryArguments, queryVariable)
{

    var domElement = document.getElementById(controlID);
    if(domElement != null ){
        if(domElement.selectedIndex > 0 ){
            queryArguments[queryVariable] = domElement.options[domElement.selectedIndex].text;
        }
        else
        {
            queryArguments[queryVariable] = '';
        }
    }
};
//-----------------------------------------------------
/*Fill queryArguments with data from control preparing it for creating from array new URL*/
POLAR.View.getQueryValueFromCheckBox = function(controlID, queryArguments, queryVariable)
{
    var domElement = document.getElementById(controlID);
    if((domElement != null)  )
	{
	    queryArguments[queryVariable] = domElement.checked;
	}
	else
	{
	    queryArguments[queryVariable] = '';
	}
};
//-----------------------------------------------------
 /* This function parses ampersand-separated name=value argument pairs from
 * the query string of the URL. It stores the name=value pairs in
 * properties of an object and returns that object. Use it like this:
 *
 * var args = getArgs( );  // Parse args from URL
 * var q = args.q || '';  // Use argument, if defined, or a default value
 * var n = args.n ? parseInt(args.n) : 10;
 */
POLAR.View.getQueryArguments = function() {
    var args = new Object( );
    var query = location.search.substring(1);     // Get query string
    var pairs = query.split('&');                 // Break at ampersand
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');          // Look for 'name=value'
        if (pos == -1) continue;                  // If not found, skip
        var argname = pairs[i].substring(0,pos);  // Extract the name
        argname = argname.toLowerCase();
        var value = pairs[i].substring(pos + 1);    // ExtractPOLAR.View.DataTable.formatDate the value
        value = decodeURIComponent(value);        // Decode it, if needed
        value = value.toLowerCase();
        args[argname] = value;                    // Store as a property
    }
    return args;                                  // Return the object
};

POLAR.View.DateTime = function() { };
POLAR.View.DataTable = function() { };

//--------------------------------------------------
POLAR.View.DataTable.configDataTable = function(dataTable) {
    // Subscribe to events for row selection
    dataTable.subscribe('rowMouseoverEvent', dataTable.onEventHighlightRow);
    dataTable.subscribe('rowMouseoutEvent', dataTable.onEventUnhighlightRow);
    //dataTable.subscribe('rowClickEvent', dataTable.onEventSelectRow); 

    // Programmatically select the first row
    //this.dataTable.selectRow(this.dataTable.getTrEl(0));
    // Programmatically bring focus to the instance so arrow selection works immediately
    //this.dataTable.focus();

    dataTable.subscribe('checkboxClickEvent', function(oArgs) {
        var elCheckbox = oArgs.target;
        var oRecord = this.getRecord(elCheckbox);
        oRecord.setData('check', elCheckbox.checked);
        if (elCheckbox.checked) {
            var elRow = this.getTrEl(elCheckbox);
            this.selectRow(elRow);
        }
        else {
            var elRow = this.getTrEl(elCheckbox);
            this.unselectRow(elRow);
            $('.selectall').attr('checked', '');
        }

        if (oArgs.event.shiftKey == true) {
            dataTable._handleStandardSelectionByMouse(oArgs);
            //sada treba selektirati sve rowove koji su chekirani i chekirati sve rovove koji su slektirani :)         
            var records = dataTable.getRecordSet().getRecords();
            for (var recordIndex = 0; recordIndex < records.length; recordIndex++) {
                var record = dataTable.getRecord(records[recordIndex]);
                //var id = record.getData('ID');
                var rowEle = dataTable.getTrEl(record);
                if (rowEle != null) {
                    var checkboxes = YAHOO.util.Dom.getElementsBy(function(ele) {
                        return ele.type == 'checkbox';
                    }, undefined, rowEle);

                    if (checkboxes.length > 0) {
                        var checkbox = checkboxes[0];
                        if (checkbox) {
                            if (dataTable.isSelected(rowEle) == true) {
                                checkbox.checked = true;
                            }
                            else {                                
                                if (checkbox.checked == true) {
                                    dataTable.selectRow(rowEle);                                
                                }
                            }
                        }
                    }
                }
            }
        }
        else {
            //dataTable._handleSingleSelectionByMouse(oArgs);
            var elTarget = oArgs.target;
            // Validate target row
            var elTargetRow = dataTable.getTrEl(elTarget);
            if (elTargetRow) {
                var oTargetRecord = this.getRecord(elTargetRow);

                // Set anchor
                this._oAnchorRecord = oTargetRecord;

                // Select only target
                //this.unselectAllRows();
                //this.selectRow(oTargetRecord);
            }


        }
    });

    /*dataTable.subscribe('rowClickEvent', function(oArgs) {
    var rowEle = oArgs.target;
    if (rowEle != null) {
    var checkboxes = YAHOO.util.Dom.getElementsBy(function(ele) {
    return ele.type == 'checkbox';
    }, undefined, rowEle);

            if (checkboxes.length > 0) {
    var checkbox = checkboxes[0];
    if (checkbox) {
    checkbox.checked = true;
    }
    }
    }    
    });*/


    $("#dataTableContainer").prepend("<div style='padding-bottom:3px' > <input type='text' class='textboxMiddle' id='dtQuickFilter'  title='" + resource.LabelsCommon.QuickFilter + "' >     <a id='clearQuickFilter' href=''>" + resource.LabelsCommon.Clear + "</a>   </div>");
    $('input[title!=""]').jqpHint();
    //Quick Filter
    var dataSource = dataTable.getDataSource();
    var filterTimeout = null;
    var updateFilter = function() {
        // Reset timeout 
        filterTimeout = null;
        // Reset sort 
        var state = dataTable.getState();
        //state.sortedBy = {key:'areacode', dir:YAHOO.widget.DataTable.CLASS_ASC}; 
        // Get filtered data
        dataSource.sendRequest(YAHOO.util.Dom.get('dtQuickFilter').value, {
            success: dataTable.onDataReturnInitializeTable,
            failure: dataTable.onDataReturnInitializeTable,
            scope: dataTable,
            argument: state
        });
    };

    YAHOO.util.Event.on('dtQuickFilter', 'keyup', function(e) {
        clearTimeout(filterTimeout);
        setTimeout(updateFilter, 600);
    });

    $("#clearQuickFilter").click(function(event) {
        event.preventDefault();
        $("#dtQuickFilter").val("");
        updateFilter();
        $('input[title!=""]').jqpHint();
    });

    /*var dataTableState = dataTable.getState();
    dataTableState.pagination.paginator.subscribe('render', function() {        
    //$("#dataTableContainer .yui-pg-container:first").prepend("<div style='float:left; '> <label>" + resource.LabelsCommon.Filter + "</label> <input type='text' id='dtQuickFilter'  ></div>");
    });*/


    /********/
    //resize correctrly coloummn inYUI datatabel and fixing bugs.
    /********/
    //za dinamcko postavlajnje sirina td ond drag resizer with mouse
    dataTable.subscribe('columnSetWidthEvent', function(args) { //renderEvent renderLoopSizeChange
        var counterN = 1;
        $('#dataTableContainer tr:eq(2) td .yui-dt-liner').each(function() {
            //$(this).css('border', 'solid 1px green');                
            var widthDiv = $(this).width(); // $('#dataTableContainer tr td:eq(3) .yui-dt-liner').width(); // - ovo radi
            $('#dataTableContainer tr td:eq(' + counterN + ')').css('width', widthDiv + 'px');
            //$('#dataTableContainer tr td:eq(' + counterN + ')').css('border', 'solid 1px green');
            //if (counterN == 3 || counterN == 6) {}
            counterN++;
        });        
        /*
        var widthTd = $('#dataTableContainer tr td:eq(3) .yui-dt-liner').width(); //- ovo radi
        $('#dataTableContainer tr td:eq(3)').css('width', widthTd + 'px');
        widthTd = $('#dataTableContainer tr td:eq(6) .yui-dt-liner').width(); //- ovo radi 
        $('#dataTableContainer tr td:eq(6)').css('width', widthTd + 'px');
        $('#testid22').remove();
        $('#idResourceName').before("<span id='testid22'>" + widthTable + "-" + widthTable2 + "</span>");*/
    });

    //za prvi put postaviti kad se ispisuje tablica uzmemo dirinu diva koji se nalazi u prvom redu (td) a koj je postavljen u definicij tablice na maxAutoWidth i to postaivmo na TD 
    //na ovaj nacin izbjegavamo neestetski veliki razmak izmedju teksta i desnog ruba celije TD.
    dataTable.subscribe('postRenderEvent', function(args) { //
        //dovoljno je uzeti sirinu div-a prvog TR jer su pravilno postalljene prilikom incijalnizacije tablice i onda te sirien primjentii na TDove
        var counterN = 1;
        $('#dataTableContainer tr:eq(2) td .yui-dt-liner').each(function() {            
            var widthDiv = $(this).width(); 
            $('#dataTableContainer tr td:eq(' + counterN + ')').css('width', widthDiv + 'px');            
            counterN++;
        });
        

        /*
        var widthTd = $('#dataTableContainer tr td:eq(3) .yui-dt-liner').width(); // - ovo radi                
        $('#dataTableContainer tr td:eq(3)').css('width', widthTd + 'px');
        var widthTd2 = $('#dataTableContainer tr td:eq(6) .yui-dt-liner').width(); // - ovo radi
        $('#dataTableContainer tr td:eq(6)').css('width', widthTd2 + 'px');
        */
        //var widthTd = dataTableContainerWidth / 3;
        //$('#dataTableContainer tr td:eq(3) .yui-dt-liner').css('width', widthTd + 'px');                
        //var widthTd = 500;
        //$('#dataTableContainer tr td:eq(3) .yui-dt-liner').css('width', widthTd + 'px'); //width(widthTd);
        //$('#dataTableContainer tr td:eq(3) .yui-dt-liner').css('border', 'solid 1px green');
        //$('#dataTableContainer tr:eq(3)').css('background-color', '#727890');
        //return;
        //alert("columnSetWidthEvent");

        //$(this).css('border', 'solid 1px green');                        
        /*
        $('#dataTableContainer tr td:eq(3)').css('border', 'solid 1px green');
        var widthTd = $('#dataTableContainer tr td:eq(3)').width();                
        //alert( $('#dataTableContainer tr td:eq(3) .yui-dt-liner').width());
        //$('#dataTableContainer tr td:eq(3) .yui-dt-liner').width(widthTd);
        $('#dataTableContainer tr td:eq(3) .yui-dt-liner').css('width', '400px'); // .yui-dt-liner
        $('#dataTableContainer tr td:eq(3)').css('width', '400px');
        //setColumnWidth 
        */
    });    
};
//--------------------------------------------------
POLAR.View.DataTable.createDefaultPaginator = function() {
    return new YAHOO.widget.Paginator({
        rowsPerPage: 50,             
            
        //template : "{PreviousPageLink} {CurrentPageReport} {NextPageLink}",
        firstPageLinkLabel: "&lt;&lt;",
        previousPageLinkLabel: "&lt;",
        nextPageLinkLabel: "&gt;",
        lastPageLinkLabel: "&gt;&gt;",
        //pageReportTemplate: "{FirstPageLink} {startRecord} - {endRecord} of the Top {totalRecords} {RowsPerPageDropdown}",   
        //pageReportTemplate:"{currentPage} of {totalPages}",
        template: '{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}',
        pageLinks: YAHOO.widget.Paginator.VALUE_UNLIMITED,
        rowsPerPageOptions: [10, 25, 50, 75, 100, 200, 300, 400, 500, 1000]
    });
};

//--------------------------------------------
POLAR.View.DataTable.createDataSource = function(inResource) {
    var dataSource = new YAHOO.util.DataSource(inResource);
    dataSource.doBeforeCallback = function(req, raw, res, cb) {
        // This is the filter function 
        var data = res.results || [],
	                    filtered = [],
	                    i, l;

        if (req) {
            req = req.toLowerCase();
            var dataLength = data.length;
            var fieldsLength = dataSource.responseSchema.fields.length;
            var tokens = req.split(/\s+/);
            var tokensLength = tokens.length;
            var fFoundToken = false;
            var fNextRow = false;
            for (i = 0; i < dataLength; ++i) {//per row in table
                //vrtimo po tokenima i mora svaki token biti nadjen u nekom od filed. Znaci raidmo AND operaciju nad tokenima
                //tek tada ubacujemo filtered.push(data[i]);
                for (k = 0; k < tokensLength; ++k) {//per token on tekst in cell 
                    for (j = 0; j < fieldsLength; ++j) {//per cell in table
                        var field = dataSource.responseSchema.fields[j];
                        var filedData;
                        if (YAHOO.lang.isObject(field) == true) {
                            filedData = data[i][field.key.toString()];
                        }
                        else {
                            if (field.toLowerCase().indexOf("url") != -1) {
                                continue;
                            }
                            filedData = data[i][field];
                        }

                        if (YAHOO.lang.isNull(filedData) == true) {
                            continue;
                        }

                        filedData = filedData.toString();
                        if (filedData.toLowerCase().indexOf(tokens[k].toString()) != -1) {
                            fFoundToken = true;
                            break;
                        }
                    }

                    if (fFoundToken == true) {
                        fFoundToken = false;
                        continue; //nasli mso ovaj token u nekom od fieldova sada idemo na sleijdeci token
                    }
                    else {//ako nismo nasli ovaj jedan token u svim poljima onda nema ssmial traziti slijdeci token vec idmeo na sleijdec row od tablice a ne an sliejdeci token
                        fNextRow = true;
                        break;
                    }
                }
                if (fNextRow == true) {
                    fNextRow = false;
                    continue; //prekidamo vrtenje po tokenima i idmeo an sleijdeci row u tablici
                }
                else {
                    filtered.push(data[i]);
                }
            }
            res.results = filtered;
        }
        return res;
    }

/*
    //Quick Filter
    var filterTimeout = null;
    var updateFilter = function() {
        // Reset timeout 
        filterTimeout = null;

        // Reset sort 
        var state = dataTable.getState();
        //state.sortedBy = {key:'areacode', dir:YAHOO.widget.DataTable.CLASS_ASC}; 

        // Get filtered data
        dataSource.sendRequest(YAHOO.util.Dom.get('dtQuickFilter').value, {
            success: dataTable.onDataReturnInitializeTable,
            failure: dataTable.onDataReturnInitializeTable,
            scope: dataTable,
            argument: state
        });
    };

    YAHOO.util.Event.on('dtQuickFilter', 'keyup', function(e) {
        clearTimeout(filterTimeout);
        setTimeout(updateFilter, 600);
    });
*/
    return dataSource;
};
//-----------------------------------------------

POLAR.View.DataTable.formatUrl = function(elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = '<a href="' + oRecord.getData('URL') + '">' + sData + '</a>';
};

POLAR.View.DataTable.formatDate = function(elCell, oRecord, oColumn, oData) {
	if(oData._pl_is_formated_) {
		elCell.innerHTML = POLAR.View.DateTime.dateToStringNoCorrection(oData);
	}
	else {
		oData._pl_is_formated_ = true;
		elCell.innerHTML = POLAR.View.DateTime.dateToString(oData);
	}
   // alert("the: " + oColumn.key + " column was resized to: " + elCell.width);
};

/*POLAR.View.DataTable.spTestingDate2 = function(elCell, oRecord, oColumn, oData) {
    elCell.innerHTML = "321341234";
    // alert("the: " + oColumn.key + " column was resized to: " + elCell.width);
};*/


POLAR.View.DataTable.formatServiceUser = function(elCell, oRecord, oColumn, sData) {
    if (sData == null) return;
    elCell.innerHTML = '<a href=' + oRecord.getData('Contact.URL') + '>' + sData + '</a>';
};

POLAR.View.DataTable.formatAssignee = function(elCell, oRecord, oColumn, sData) {
    if (sData == null) return;
    elCell.innerHTML = '<a href=' + oRecord.getData('User.URL') + '>' + sData + '</a>';
};

POLAR.View.DataTable.formatTeam = function(elCell, oRecord, oColumn, sData) {
    if (sData == null) return;
    elCell.innerHTML = '<a href=' + oRecord.getData('Team.URL') + '>' + sData + '</a>';
};

POLAR.View.DataTable.formatAccount = function(elCell, oRecord, oColumn, sData) {
    if (sData == null) return;
    elCell.innerHTML = '<a href=' + oRecord.getData('Account.URL') + '>' + sData + '</a>';
};
//----------------------------------------
// convert UTC date to our custom date format with applied time zone
// date format and time zone are PHD specific settings
POLAR.View.DateTime.dateToString = function(date) {
    try {
		var minutes = parseInt(TIME_ZONE_OFFSET_MINUTES);
        if (typeof date === "string") {
            date = Date.parse(date);
            date.add({ minutes: minutes });
        } else {
            date.add({ minutes: minutes });
        }
        
        if (OVERRIDE_DATE_TIME_FORMAT) {
            return date.toLocaleString();
        } else {
            return date.toString(DATE_TIME_FORMAT);
        }
    } 
    catch (e) {
        return "";
    }
};

POLAR.View.DateTime.dateToStringNoCorrection = function(date) {
    try {
		//var minutes = parseInt(TIME_ZONE_OFFSET_MINUTES);
        if (typeof date === "string") {
            date = Date.parse(date);
            //date.add({ minutes: minutes });
        } else {
            //date.add({ minutes: minutes });
        }
        
        if (OVERRIDE_DATE_TIME_FORMAT) {
            return date.toLocaleString();
        } else {
            return date.toString(DATE_TIME_FORMAT);
        }
    } 
    catch (e) {
        return "";
    }
};
//-----------------------------------------------------
POLAR.View.DateTime.stringToDate = function(str) {
    try {
		return Date.parse(str);
		/*var date = POLAR.Util.stringToDate(str);		
		var minutes = parseInt(TIME_ZONE_OFFSET_MINUTES) * -1;
        date.add({ minutes: minutes });
        
        if (OVERRIDE_DATE_TIME_FORMAT) {
            return date.toLocaleString();
        } else {
            return date.toString(DATE_TIME_FORMAT);
        }*/
    } 
    catch (e) {
        return "";
    }
};
//-----------------------------------------------------
POLAR.View.DataTable.configDeleteUndelete = function(config) {
    var arg = { dataTable: config.dataTable, items: config.dataTableItems };
   
    if (config.dataTableDeleteButton != null && config.dataTableDeleteButton != undefined) {        
        var oDeleteButton = new YAHOO.widget.Button(config.dataTableDeleteButton, { onclick: { fn: POLAR.View.DataTable.deleteResources, obj: arg} });         
    }
    else if (config.dataTableUndeleteButton != null && config.dataTableUndeleteButton != undefined) {
		var oDeleteButton = new YAHOO.widget.Button(config.dataTableUndeleteButton, { onclick: { fn: POLAR.View.DataTable.undeleteResources, obj: arg} });         
    }
};
//-----------------------------------------------------
POLAR.View.DataTable.addIdToUrlBasedOnRegex = function(url, id, pattern) {
    var regex = new RegExp(pattern);
    var results = regex.exec(url);

    if (null != results) {
        var insertPosition = results[0].length
        return url.substring(0, insertPosition) + ';' + id + url.substring(insertPosition, url.length);
    }
}
//-------------------------------------------------------
POLAR.View.DataTable.deleteResources = function(v, arg) {
    var records = arg.dataTable.getRecordSet().getRecords();
    var itemsToDelete = new Array();

    for (var recordIndex = 0; recordIndex < records.length; recordIndex++) {
        var record = arg.dataTable.getRecord(records[recordIndex]);
        var id = record.getData('ID');
        var uri = record.getData('URI');
        var rowEle = arg.dataTable.getTrEl(record);

        if (rowEle != null) {
            var checkboxes = YAHOO.util.Dom.getElementsBy(function(ele) {
                return ele.type == 'checkbox';
            }, undefined, rowEle);

            if (checkboxes.length > 0) {
                var checkbox = checkboxes[0];
                if (checkbox && checkbox.checked) {
                    for (var itemIndex = 0; itemIndex < arg.items.length; itemIndex++) {
                        if (arg.items[itemIndex].ID == id || arg.items[itemIndex].URI == uri) {
                            itemsToDelete.push({
                                record: record,
                                resource: arg.items[itemIndex]
                            });
                            break;
                        }
                    }
                }
            }
        }
    }

    for (var itemIndex = 0; itemIndex < itemsToDelete.length; itemIndex++) {
        var item = itemsToDelete[itemIndex];

        var deleteFunc = function(itemToDelete) {
            POLAR.View.asyncDelete(itemToDelete.resource.URI, function(response) {
                arg.dataTable.deleteRow(itemToDelete.record);
            });
        };

        deleteFunc(item);
    }
};
//-----------------------------------------------------
POLAR.View.DataTable.undeleteResources = function(v, arg) {
    var records = arg.dataTable.getRecordSet().getRecords();
    var itemsToDelete = new Array();

    for (var recordIndex = 0; recordIndex < records.length; recordIndex++) {
        var record = arg.dataTable.getRecord(records[recordIndex]);
        var id = record.getData('ID');
        var uri = record.getData('URI');
        var rowEle = arg.dataTable.getTrEl(record);

        if (rowEle != null) {
            var checkboxes = YAHOO.util.Dom.getElementsBy(function(ele) {
                return ele.type == 'checkbox';
            }, undefined, rowEle);

            if (checkboxes.length > 0) {
                var checkbox = checkboxes[0];
                if (checkbox && checkbox.checked) {
                    for (var itemIndex = 0; itemIndex < arg.items.length; itemIndex++) {
                        if (arg.items[itemIndex].ID == id || arg.items[itemIndex].URI == uri) {
                            itemsToDelete.push({
                                record: record,
                                resource: arg.items[itemIndex]
                            });

                            break;
                        }
                    }
                }
            }
        }
    }

    for (var itemIndex = 0; itemIndex < itemsToDelete.length; itemIndex++) {
        var item = itemsToDelete[itemIndex];

        var deleteFunc = function(itemToDelete) {
            POLAR.View.asyncPut(itemToDelete.resource.URI, undefined, function(response) {
                arg.dataTable.deleteRow(itemToDelete.record);
            });
        };

        deleteFunc(item);
    }
};
//-----------------------------------------------------
POLAR.View.DataTable.selectOrUnselectAllCheckboxes = function(colCheckbox, dataTable) {
    var checked = colCheckbox.checked;
    var records = dataTable.getRecordSet().getRecords();
    for (var recordIndex = 0; recordIndex < records.length; recordIndex++) {
        var record = dataTable.getRecord(records[recordIndex]);
        var id = record.getData('ID');
        var rowEle = dataTable.getTrEl(record);

        if (rowEle != null) {
            var checkboxes = YAHOO.util.Dom.getElementsBy(function(ele) {
                return ele.type == 'checkbox';
            }, undefined, rowEle);

            if (checkboxes.length > 0) {
                var checkbox = checkboxes[0];
                if (checkbox) {                    
                    checkbox.checked = checked;
                    if (checked == true) {
                        dataTable.selectRow(rowEle);
                    }
                    else { 
                        dataTable.unselectRow(rowEle);
                    }                    
                }
            }           
        }
    }
    
    dataTable.doBeforePaginatorChange = function(oPaginatorState) {
        colCheckbox.checked = false;
        return true;
    }
};

//------------------------------------------------------------------------------------
//url - "http://localhost:5650/phd/incidents/team/2?maxresults=200"
//return - "http://localhost:5650/phd/incidents/team/2"
POLAR.Util.RemoveQueryPartFromURL = function(url) {
    if (url.indexOf('?') > 0) {
        return url.substring(0, url.indexOf('?'));
    }
    else {
        return url;
    }
}
//------------------------------------------------------------------------------------
//var url = "http://localhost:5650/phd/incidents/team/2?maxresults=200";
//var virtualUrl = "http://localhost:5650/phd";
//return - "incidents/team/2?maxresults=200"
POLAR.Util.GetPathAndQueryPartFromURL = function(virtualUrl, url) {
    return url.substring(virtualUrl.length + 1, url.length);
}

//------------------------------------------------------------------------------------
//try find is in resource.UserPreference.UserRecentItems exist sam URL (without Query part like this and if exist replace it (withi it query part current URL.
//we do tid for remplaber last URL in navigation
POLAR.View.GetUrlSimilarFromUserRecentItems = function(inUrl) {

    //if we do not have query
    //inUrl.indexOf('?')
    var url = inUrl;
    if (typeof (resource.UserPreference) !== "undefined" && resource.UserPreference != null && typeof (resource.UserPreference.UserRecentItems) !== "undefined" && resource.UserPreference.UserRecentItems != null) {
        //sad trazimo ima li u UserRecentItems iti jedna link koji se mapira na trenutni URL. Otkinemo Query dio i usporedimo, ako ima zamjenimo taj URL iz UserRecentItems  sa ovim poslatim
        var UrlFromUserRecentItemsFinder = function(item, urlWithoutQueryPart) {
            var url = POLAR.Util.RemoveQueryPartFromURL(item.Url);
            if (url == urlWithoutQueryPart) {
                return item.Url;
            }
            else {
                return 0;
            }
        }
        var urlWithoutQueryPart = POLAR.Util.RemoveQueryPartFromURL(url);
        //if have not query part for now do not go to find
        if (urlWithoutQueryPart != url) {
            var urlFromUserRecentItems = POLAR.Util.Find(UrlFromUserRecentItemsFinder, resource.UserPreference.UserRecentItems, urlWithoutQueryPart);
            if (urlFromUserRecentItems != 0) {
                url = urlFromUserRecentItems; //alert(urlFromUserRecentItems);
            }
        }
    }
    return url;
}
//------------------------------------------------------------------------------------
POLAR.Util.Map = function(fn, arrayX) {
    var i = 0; //MUST be var
    for (; i < arrayX.length; i++) {
        arrayX[i] = fn(arrayX[i]);
    }
}
//------------------------------------------------------------------------------------
POLAR.Util.Reduce = function(fn, arrayX, init) {
    var s = init; //MUST be var
    var i = 0; //MUST be var
    for (; i < arrayX.length; i++) {
        s = fn(s, arrayX[i]);
    }
    return s;
}
//------------------------------------------------------------------------------------
POLAR.Util.ReduceExt = function(fn, arrayX, init1, init2) {
    var s = init1; //MUST be var
    var i = 0; //MUST be var
    for (; i < arrayX.length; i++) {
        s = fn(s, arrayX[i], init2);
    }
    return s;
}
//------------------------------------------------------------------------------------
//Iterate over arrayX with call ing function fn and stop when funtion fn return != 0
//fn - function which called for each element of arrayX and passwd in criteria value
//arrayX - array through we iterate
//criteria - value which we passed to function fn
POLAR.Util.Find = function(fn, arrayX, criteria) {
    var s = 0; //MUST be var
    var i = 0; //MUST be var
    for (; i < arrayX.length; i++) {
        s = fn(arrayX[i], criteria);
        if (s != 0) {
            return s;
        }
    }
    return s;
}
//------------------------------------------------------------------------------------
POLAR.Util.DuplicateArray = function(array) {
    var a = new Array();
    for (var ia = 0; ia < array.length; i++) {
        a[ia] = array[ia];
    }
    return a;
}
//----------------------------------------------------------------------------
//permissionItem - jedan od elemenata iz array _resRep.UserCurrentResource.ResorucePermissions tj. class PermissionItem
//permissionItem - je elemenata array navigationItems.submenu.itemdata
//return - je elemenat array iz stabla _resRep.UserCurrentResource.ResorucePermissions koji ima isti string ResorucePermission[n].URN kao i poslati string iz navigationItems.submenu.itemdata
POLAR.Util.GetPermissioneForUrnFinder = function(permissionItem, criteria) {
    if (permissionItem.URN == criteria) {
        if (permissionItem.GET == true) {
            return true;
            //return UserResourcePermissions.VirtualUrl + "/api/" + permissionItem.URN;
        }
    }
    return 0;
}		
//------------------------------------------------------------------------------------
/*Example of use:
    var uriTemplateX = "/incident/{id}/template/";
    var urlX = "http://www.example.com/myhelpdesk/incident/1/template";
    var mappingResoult = POLAR.View.GetMappingResult(urlX, uriTemplateX);

    urlIn - URI kojega pokusavamo mapirati na trenutni URI Temaplate , najcesce je ovo link u address baru tj. window.location.href
    uriTemplateIn - najscesce URI Template a i nemora biti
*/
//-----------------------------------------------------
POLAR.View.GetMappingResult = function(uriIn, uriTemplateIn) {
    var uri = uriIn.toLowerCase();
    //cut  virtual part of URL
    var index = uri.indexOf(UserResourcePermissions.VirtualUrl);
    if (index != -1) {
        uri = uri.substring(UserResourcePermissions.VirtualUrl.length, uri.length);
    }

    var uriTemplate = uriTemplateIn.toLowerCase();

    //prepare URI Tempalte, on beggining must be "/" for correct parsing "path" part of URL
    if (uri.charAt(0) != "/") {
        uri = "/" + uri;
    }
    if (uriTemplate.charAt(0) != "/") {
        uriTemplate = "/" + uriTemplate;
    }

    //izvrtimo sve segmente iz oba URL na nacin da iz URI tempalte kad naidejemo na URI template varaijblu sa {nn} probamo je zamjeniti sa istovjetnmi segmentom iz URLa i na kraju iz URL tempaltea
    //dobiti URI koji treba biti identican URL-u . Na kraju kada exandamo URi template moramo dobiti pocetni URL
    //prvi korak je segmentirati oba URI-ija u dva arraya, sve operacije radim ona "path" dijelo od URIija

    //pretvorimo oba URIije u arraye..
    //SP:19102009 uriTemplate = jQuery.url.setUrl(uriTemplate).attr("path");
    //SP:19102009 uri         = jQuery.url.setUrl(uri).attr("path"); //form "http://www.example.com/myhelpdesk/incident/1" return "myhelpdesk/incident/1"
    var segmentsUriTemplate = jQuery.url.setUrl(uriTemplate).segmentsArray();
    var segmentsUrl = jQuery.url.setUrl(uri).segmentsArray();

    //ovo radimo da mi izbjegli virutalni path -> ali ako imamo FullUrl onda to netreba
    //sada trazimo prvo istovjetno pojavljivanje segmenta iz URI Tempaltea (osim ako nije URI Tempalte Varijabla tj. "{X}" ) unutar URLa ako toga nema onda ovaj URL se ne moze machirati na ovaj URI tempalte
    //vrtimo listu segmenata URI Template i gledamo kad cemo naletjeti na istoimeni string ako niakkao ne nelatimo vracamo false a ako naeltimo idmeo dlaje. S tim da kao je u URI tempalte {} odna preskacemo i idmeo dalje.
    //na pocetku UTI temaptle en smiej biti {} tj. pretpostavlajmo da nije niakda. jer mi nemamo takvu konstrukciju linkova.
    //Map nam ne moze vratiti nikaakv rezultat je li se ili ne mapira pa stoga idemo sa reduce.
    /*function FindFirstSegment(item, criteria)
    {
    if (item == criteria) { return item; }
    else { return 0; }
    }
    var flagFindFirstSegment = POLAR.Util.Find(FindFirstSegment, segmentsUrl, segmentsUriTemplate[0]);
    if (flagFindFirstSegment != 0)
    {  }*/
    /*

    var firstSegment = -1;
    for (var is = 0; is < segmentsUrl.length; is++) {
    if (segmentsUrl[is] == segmentsUriTemplate[0]) {
    firstSegment = is;
    break;
    }
    }

    if (firstSegment == -1) {
    return false;
    }

    //recimo da sada imamo poziciju prvog istovjetnog elementa izmadjeu URI templatea i URL. Sada reorganziramo URL listu da je prvi elemenat onaj koji se poklapa.
    var newSegmentsUrl = [];
    for (var i = 0; i < segmentsUrl.length - firstSegment; i++) {
    newSegmentsUrl[i] = segmentsUrl[i + firstSegment];
    }
    */
    var newSegmentsUrl = segmentsUrl;
    //TODO: prvo provjera imamo li sada isti broj segmenata
    if (segmentsUriTemplate.length != newSegmentsUrl.length) {
        return false;
    }

    //sada vrtimo URLTemplate listu i mapiramo segment po segment ..
    for (var i = 0; i < segmentsUriTemplate.length; i++) {
        var posX = segmentsUriTemplate[i].indexOf('{');
        if (posX != -1) {
            segmentsUriTemplate[i] = newSegmentsUrl[i];
        }
    }

    //sada trebamo izvrtjeti obje liste i vidjeti je li se svi segmenti slazu?
    var sameArray = true;
    for (var i = 0; i < segmentsUriTemplate.length; i++) {
        if (segmentsUriTemplate[i] == newSegmentsUrl[i]) {
            continue;
        }
        else {
            sameArray = false;
            break
        }
    }
    return sameArray; //true if URL map in URI Tempalte , false if not
}
//-----------------------------------------------------------------------------------------------------------
POLAR.View.CreateTopNavigation5 = function() {
    var oMenuBar = new YAHOO.widget.MenuBar("mymenubar2", { lazyload: true, showdelay: 0, submenuhidedelay: 0, iframe: false });    
    if (typeof (navigationconfiguration) === "undefined") {
        return;
    }
    if (typeof (navigationconfiguration.items) === "undefined") {
        return;
    }
    
    function expandUrl(obj) {
		$.each(obj, function (key, val) {			
			if(val.url !== undefined)
			{
				val.url = BASE_URL + val.url;
			}
			else if(YAHOO.lang.isObject(val))
			{
				expandUrl(val);
			}
		});
	}
    
    expandUrl(navigationconfiguration.items);
    
    oMenuBar.addItems(navigationconfiguration.items);
    oMenuBar.render("topNavigation2");
    
    // Add a "show" event listener for each submenu.
    function onSubmenuShow() {
        var oIFrame,
				oElement,
                nOffsetWidth;
        // Keep the left-most submenu against the left edge of the browser viewport
        if (this.id == "yahoo") {
            YAHOO.util.Dom.setX(this.element, 0);
            oIFrame = this.iframe;
            if (oIFrame) {
                YAHOO.util.Dom.setX(oIFrame, 0);
            }
            this.cfg.setProperty("x", 0, true);
        }
        /*Need to set the width for submenus of submenus in IE to prevent the mouseout event from firing prematurely when the user mouses off of a MenuItem's text node.*/
        if ((this.id == "filemenu" || this.id == "editmenu") && YAHOO.env.ua.ie) {
            oElement = this.element;
            nOffsetWidth = oElement.offsetWidth;
            /*Measuring the difference of the offsetWidth before and after setting the "width" style attribute allows us to compute the about of padding and borders applied to the element, which in turn allows us to set the "width" property correctly.*/
            oElement.style.width = nOffsetWidth + "px";
            oElement.style.width = (nOffsetWidth - (oElement.offsetWidth - nOffsetWidth)) + "px";
        }
    }
    // Subscribe to the "show" event for each submenu
    oMenuBar.subscribe("show", onSubmenuShow);    
}
//---------------------------------------------------------------------------------------------
POLAR.View.CreateUserPreference = function() {
    if (typeof (resource) === "undefined") {
        POLAR.View.AddDataToMessageBoxData("typeof (resource) === 'undefined' - TODO: we not yet implement resource here");
        return;
    }

    var strUserRecentItems = "";
    if (typeof (resource.UserPreference) !== "undefined" && resource.UserPreference != null && typeof (resource.UserPreference.UserRecentItems) !== "undefined" && resource.UserPreference.UserRecentItems != null) {
        for (var i = 0; i < resource.UserPreference.UserRecentItems.length; i++) {
            if (typeof (resource.UserPreference.UserRecentItems[i].Url) !== "undefined" && resource.UserPreference.UserRecentItems[i].Url != null) {
                var url = resource.UserPreference.UserRecentItems[i].Url.toString();
                var uri = resource.UserPreference.UserRecentItems[i].Uri.toString();
                uri = uri.substring(0, 20);
                //OLD 2010-0-18 strUserRecentItems = strUserRecentItems + "<span class='item_selected'> <a class='recentItemXX' href='" + url + "'>" + uri + "</a></span>"; /*+ resource.UserPreference.UserRecentItems[i].CreatedOn*/
                strUserRecentItems = strUserRecentItems + "<span class='recentListItem'> <a href='" + url + "'>" + uri + "</a></span>";
            }
        }
    }
    $("#IdUserPreference").append(strUserRecentItems);
};
//---------------------------------------------------------------------------------------------
/* AutoCompleteLookup*/
//---------------------------------------------------------------------------------------------
/* Attaches new lookup element after the element with given ID.
* Make sure elementId has last character as digit less then 10, as it will be increased for creating new unique ID
* e.g. status0 => status1
* same for linkId
* @param elementId - element id of div containig lookup control
* @param linkId - element id of a that will be updated on autocomplete select
* @param autocompleteConfig - config object for autocomplete control
* @return - new autocomplete object created, or null if can't create it */
POLAR.Widget.appendNewLookupControl = function(elementId, linkId, autocompleteConfig, addAfterElementWithId) {
    if (elementId == null || elementId == undefined) {
        return null;
    }

    // get counter from last digit of elementId so we can create new id
    var counter = parseInt(elementId.substr(elementId.length - 1));
    counter++;
    var newElementId = elementId.substring(0, elementId.length - 1) + counter;

    // make sure our new ID is not used
    if ($('#' + newElementId).length !== 0) {
        return null;
    }

    // get counter from last digit of linkId so we can create new id
    counter = parseInt(linkId.substr(linkId.length - 1));
    counter++;
    var newLinkId = linkId.substring(0, linkId.length - 1) + counter;

    // make sure our new ID is not used
    if ($('#' + newLinkId).length !== 0) {
        return null;
    }

    // clone lookup control and add it after the current one
    var autocompleteClone = $('#autocomplete-template').clone();
    autocompleteClone.css('display', 'block');
    autocompleteClone.attr('id', newElementId);
    autocompleteClone.find('#autocomplete-template-link').attr('id', newLinkId);
    $('#' + addAfterElementWithId).after(autocompleteClone);
    autocompleteConfig.id = newElementId;
    autocompleteConfig.linkID = newLinkId;
    return new POLAR.Widget.AutoCompleteLookup(autocompleteConfig);
}
//-----------------------------------------------------
POLAR.Widget.AutoCompleteLookup = function(obj) {

    // remember object property from inicialization
    this._idAutoCompleteLookup = obj.id;
    this._rootEle = YAHOO.util.Dom.get(obj.id);
    this._url = obj.url; //http://localhost/phd/incidents
    this._urlItem = obj.urlItem; //http://localhost/phd/incident/
    this._customDataTable = obj.customDataTable;
    this._multipleControlsAllowed = obj.multipleControlsAllowed;
    this._config = obj;
    this._autocompleteXHRDataSource;
    this._customChangeLinkedControl = obj.customChangeLinkedControl; //funkcija koja se poziva ako treba nesto dodatno ruaditi prilikom updejta Linked Control
    this._autoCompleteData = obj.autoCompleteData; //{ schema: ['UserName', 'FirstName', 'LastName', 'Email', 'ID'], query: '?maxresults=60&textsearch={0}*' },
    this._lookupPanelData = obj.lookupPanelData; //{fields: xxxx, columnDefinitions: yyyyy}
    this._dataTableData = obj.dataTableData;
    this._onAdd = obj.onAdd;
    this._onRemove = obj.onRemove;

    //Name of identificator, usualy this is a 'ID' string but in some resoruce like Document this is a 'Title' (/document/software) if it not defined must be 'ID'
    if (!YAHOO.lang.isUndefined(obj.propertyIdName) && !YAHOO.lang.isNull(obj.propertyIdName)) {
        this._propertyIdName = obj.propertyIdName;
    }
    else {
        this._propertyIdName = 'ID';
    }

    //LinkedEntity control start code 
    this._linkID = obj.linkID;
    //propertyName - je npr. "Contact" a to je unutar JSON objekta, tj. resoruce, tj. JS objekta /incident.Contact pod objekt na kojega pokazuje ovaj link
    this._propertyName = obj.propertyName;
    //resourceHolder - je ovakva strutkura var filterResource = { Contact: {},    User: {},    Account: {},    Team: {} }; - znaic simulacija /incident resource  //ili sami /incident
    //???ako je resourceHolder nedefiniran onda znaci da radimo na formi od jendog resoruce npr /incident
    //???ako je resourceHolder definiran onda smo na /incidens i ovo je strutkura koja simulira /incident resource
    this._resourceHolder = obj.resourceHolder;
    //subResource - je incident.Contact - znaci to nije onaj glavni resource kojiimamona /incident formi
    this._subResource = this._resourceHolder[this._propertyName];

    // this is hack so we don't mix empty resource (who has ID 0) with our non-selected (unassigned) value (also ID 0)
    // when creating the control if we get ID 0 we assume it is from empty resource and change it to -1
    if (this._subResource && this._subResource[this._propertyIdName] === 0) {
        this._subResource[this._propertyIdName] = -1;
    }

    var that = this; //closure for panel onclick function

    // initialize unassigned button
    if (this._config.allowUnassignedValue) {
        var unassignButton = $(this._rootEle).find('.lookupSetEmpty');
        $(unassignButton).click(function() {
            that._changeOnLinkedControl(0);
        });
        $(unassignButton).show();
    }

    this.setNewUrl = function(newUrl) {
        this._url = newUrl;
        this._autocompleteXHRDataSource.liveData = newUrl;
    };

    //LinkedEntity control methods
    //poziv ove funckeij se odvija kad dodatmo entitet a treba ga dodati i u link
    //Default function whic you call when you want update link control 
    this._changeOnLinkedControl = function(id, uri) {
        //todo/ needs to be handled properly via uri templating engine, not as a quick hack
        // replace uri template place holder with actual id
        var url = "";
        if (uri === undefined) {
            url = this._urlItem + id;
        } else {
            url = uri;
        }

        // ID 0 means that selection has to stay unassigned, we don't need to do async get on resource, just add it to filter
        // create fake result so control can display it as "<unassigned>"
        if (id == 0) {
            var unassignedLabel = resource.LabelsCommon.Unassigned ? resource.LabelsCommon.Unassigned : 'Unassigned';
            var selectedResourceMockup = { ID: 0, Name: '(' + unassignedLabel + ')', URL: '' };

            this.addResourceAsSelected(selectedResourceMockup);

            this.renderLinkedEntity();

            if (this._customChangeLinkedControl) {
                this._customChangeLinkedControl(this._subResource);
            }

            // if we set to have multiple controls, then hide the select button of already used ones, only newest unused one gets to have it
            if (this._multipleControlsAllowed === true) {
                this.appendNewControl();
            }

            return;
        }

        var thisCopy = this;
        POLAR.View.asyncGet(url, function(newSubResource) {
            //thisCopy._createOrUpdate(newSubResource);
            //ako postojei _dataTableData onda se rezultati ispisuju u tablicu a u ne Linked kontrolu
            if (thisCopy._dataTableData) {
                //vrtimo po fildovima i izvlacimo imena fildova za datatable i kontruiramo row na osnovu tih imena i onog sto smo dobili nazad preko AJAXa
                var row = {};
                
                var getResourceValue = function(fieldPath) {
					$.each(fieldPath.split("."), function(key, val) {
						
					});
                };
                
                for (var i = 0; i < thisCopy._dataTableData.fields.length; i++) {
                    var field = thisCopy._dataTableData.fields[i];                    
                    if (typeof field == "string") {
						if (-1 == field.indexOf('.')) {
							row[field.toString()] = newSubResource[field.toString()];
						}
						else {
							row[field.toString()] = newSubResource[field.toString().split(".")[0]][field.toString().split(".")[1]];
						}
                    }
                    else if (typeof field == "object") {
						if (-1 == field.key.indexOf('.')) {
							row[field.key.toString()] = newSubResource[field.key.toString()];
						}
						else {
							row[field.key.toString()] = newSubResource[field.key.toString().split(".")[0]][field.key.toString().split(".")[1]];
						}
                    }
                }
                thisCopy._dataTable.addRow(row);
                thisCopy._onAdd(newSubResource);
                /*thisCopy._dataTable.addRow({
                'Title': newSubResource['Title'],
                'ID': newSubResource['ID'],
                'URL': newSubResource['URL']
                });*/
            } else {
                thisCopy.addResourceAsSelected(newSubResource);

                thisCopy.renderLinkedEntity();

                if (thisCopy._customChangeLinkedControl) {
                    thisCopy._customChangeLinkedControl(newSubResource);
                }
            }
        });

        // if we set to have multiple controls, then hide the select button of already used ones, only newest unused one gets to have it
        if (this._multipleControlsAllowed === true) {
            this.appendNewControl();
        }
    };

    /**
    * Sets a resource as selected and stores it's value into user provided data container. 
    * Set resource will be used internally for displaying selected resource.
    */
    this.addResourceAsSelected = function(newResource) {
        this._subResource = newResource;

        var valueToAdd = newResource[this._propertyIdName];

        // if we are storing multiple autocomplete selections, add it to array
        if (this._multipleControlsAllowed === true) {
            if (!($.isArray(this._resourceHolder[this._propertyName]))) {
                this._resourceHolder[this._propertyName] = [];
            }
            if (this._resourceHolder[this._propertyName].indexOf(valueToAdd) === -1) {
                this._resourceHolder[this._propertyName].push(valueToAdd);
            }
        } else {
            this._resourceHolder[this._propertyName] = this._subResource;
        }
    };

    /**
    * Adds a auto-complete-lookup control after this one. Hides select buttons and sets remove buttons for older controls before the new one.
    */
    this.appendNewControl = function() {
        $(this._rootEle).find('.pl-lookup-panel-show').hide();
        $(this._rootEle).find('.lookupSetEmpty').hide();
        var newControl = POLAR.Widget.appendNewLookupControl(this._idAutoCompleteLookup, this._linkID, this._config, this._idAutoCompleteLookup);
        if ($.isArray(this._config.listOfControlsToUpdate)) {
            this._config.listOfControlsToUpdate.push(newControl);
        }
    };

    //Method for render LinkedEntity control
    this.renderLinkedEntity = function() {
        //iscrtava podatke na linku i ako postoje
        if (!this._subResource || (this._subResource.ID !== 0 && !this._subResource.URL) || (this._subResource.ID !== 0 && !this._subResource.ID)) {
            //if (!this._subResource || !this._subResource.URL || !this._subResource.ID) {
            $('#' + this._linkID).prev('.pl-autocomplete').children('.pl-autocomplete-input').show();
            return false;
        }
        else {
            $('#' + this._linkID).prev('.pl-autocomplete').children('.pl-autocomplete-input').hide();
        }

        if (this._customChangeLinkedControl) {
            this._customChangeLinkedControl(this._subResource);
        }

        //na link sa ID "contactLink" dodaje url , klasu i tekst na kraju kreira link oblika <a id="contactLink" class="linkedEntity" href="http://localhost:5650/phd/contact/6">Anonymous Contact</a>
        $('#' + this._linkID).attr({ href: this._subResource.URL || '#', 'class': 'linkedEntity' });
        $('#' + this._linkID).html(this._subResource ? this._subResource.Name || this._subResource.Title : '');

        //dodaj remove icon ako ne postoji i dodaj click event
        this._removeIcon = $('#' + this._linkID).next('.removeLE2');
        //this._removeIcon = $('#' + this._linkID).prev('.removeLE2');
        if (this._removeIcon.length == 0) {
            //this._removeIcon = $('<a href="#"/>');
            this._removeIcon = $('<span class="removeLE2">&nbsp;</span>');
            //$('#' + this._linkID).before(this._removeIcon);
            $('#' + this._linkID).after(this._removeIcon);
            //this._removeIcon.addClass('removeLE2');

            //sprema u ovu ikonu cijeli ovaj this objekt da bi se moglo docido ovih podatak u click eventu od ive ikone this._removeIcon.click()
            this._removeIcon.data('_LEobj', this);

            //dodaje clicke event na remove ikonu
            var _this = this;
            this._removeIcon.click(function(event) {
                event.preventDefault();
                event.stopPropagation();
                var linkedEntity = $(this).data('_LEobj');
                if (linkedEntity._multipleControlsAllowed === true) {
                    $('#' + linkedEntity._idAutoCompleteLookup).remove();

                    var storage2 = linkedEntity._resourceHolder[linkedEntity._propertyName];
                    var value2 = linkedEntity._subResource[linkedEntity._propertyIdName];
                    if (storage2.indexOf(value2) != -1) {
                        storage2.splice(storage2.indexOf(value2), 1);
                    }
                    return false;
                } else {
                    var objSubResource1 = linkedEntity._resourceHolder[linkedEntity._propertyName];
                    objSubResource1[linkedEntity._propertyIdName] = 0;

                    if (linkedEntity.onRemove) {
                        linkedEntity.onRemove.apply(linkedEntity, []);
                    }
                    $('#' + linkedEntity._linkID).html('');
                    linkedEntity._removeIcon.unbind('click');
                    linkedEntity._removeIcon.data('_LEobj', null);
                    linkedEntity._removeIcon.remove(); //must be first removed
                    var autocompleteInput = $('#' + linkedEntity._linkID).prev('.pl-autocomplete').children('.pl-autocomplete-input');
                    autocompleteInput.show();
                    autocompleteInput.val('');
                    autocompleteInput.focus();

                    if (_this._customChangeLinkedControl) {
                        _this._customChangeLinkedControl();
                    }
                }

                return false;
            });

            /*this._removeIcon.hover(function(event) {
            //$(this).fadeOut(100); $(this).fadeIn(500); 
            });*/
            //$("li.fade").hover(function() { $(this).fadeOut(100); $(this).fadeIn(500); });

        }
        return true;
    };
    this.renderLinkedEntity();
    //LinkedEntity control end code


    //var panelWidth = ($(window).width() / 2).toString() + 'px';
    //var panelHeight = ($(window).height() / 2).toString() + 'px';
    //Lookup Pnale Control        
    this._lookupPanel = function() {
        // QUIRKS FLAG, FOR BOX MODEL
        var IE_QUIRKS = (YAHOO.env.ua.ie && document.compatMode == 'BackCompat');
        // UNDERLAY/IFRAME SYNC REQUIRED
        var IE_SYNC = (YAHOO.env.ua.ie == 6 || (YAHOO.env.ua.ie == 7 && IE_QUIRKS));
        // PADDING USED FOR BODY ELEMENT (Hardcoded for example)
        var PANEL_BODY_PADDING = (10 * 2) // 10px top/bottom padding applied to Panel body element. The top/bottom border width is 0

        $(POLAR.View.getElementByClassName('pl-lookup-panel-show', this._rootEle)).unbind('click');

        panel = new YAHOO.widget.Panel(POLAR.View.getElementByClassName('pl-lookup-panel', this._rootEle), {
            close: true,
            draggable: true,
            /*modal:true,*/
            width: ($(window).width() / 2).toString() + 'px', //'650px',
            height: ($(window).height() / 2).toString() + 'px', //'450px',
            autofillheight: "body",
            constraintoviewport: true,
            fixedcenter: true,
            underlay: 'shadow',
            visible: false,
            effect: { effect: YAHOO.widget.ContainerEffect.FADE, duration: 0.2 },
            context: [POLAR.View.getElementByClassName('pl-lookup-panel-show', this._rootEle), 'tl', 'bl']
        });

        //On press ESC key hide panel
        var kl = new YAHOO.util.KeyListener(
                    document,
                    { keys: 27 },
                    { fn: panel.hide, scope: panel, correctScope: true }
                 );
        panel.cfg.queueProperty("keylisteners", kl);

        //Press CTRL+Y to Show lookup popup 
        /*var kl2 = new YAHOO.util.KeyListener(
        document,{ ctrl: true, keys: 89 },
        { fn: panel.show, scope: panel, correctScope: true });
        kl2.enable();*/

        this._panel = panel;
        var thisCopy = this;
        panel.beforeShowEvent.subscribe(function() {
            //thisCopy._customLookupPanel();
            if (thisCopy._customLookupPanel) {
                //alert("stari kod za lookup, promijeni ga u novi");
                thisCopy._customLookupPanel();
            }
            else { //new code
                var combinedUrl = thisCopy._url;
                if (-1 == combinedUrl.indexOf("?")) {
                    combinedUrl += '?maxresults=60';
                }
                else {
                    combinedUrl += '&maxresults=60';
                }

                thisCopy.dataSource = new YAHOO.util.DataSource(combinedUrl);
                thisCopy.dataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
                thisCopy.dataSource.responseSchema = {
                    resultsList: 'Items',
                    fields: thisCopy._lookupPanelData.fields
                };
                onLookupPanelSelectionAdd = function(id, uri) {
                    if (thisCopy._onChange !== undefined && thisCopy._onChange !== null) {
                        thisCopy._onChange(id, uri);
                    }

                    thisCopy._panel.hide();
                    thisCopy._changeOnLinkedControl(id, uri);
                };
                thisCopy.customContactFormatter = function(elCell, oRecord, oColumn, oData) {
                    var id = oRecord.getData(thisCopy._propertyIdName);
                    var uri = oRecord.getData("URI");
                    //elCell.innerHTML = '<div class="add" onclick="return onLookupPanelSelectionAdd(' + '\'' + id + '\'' + ');"></div>';
                    $("<div>").attr("class", "add").click(function() { onLookupPanelSelectionAdd(id, uri) }).appendTo(elCell);
                };

                YAHOO.widget.DataTable.Formatter.customContact = thisCopy.customContactFormatter;
                thisCopy.dataTable = new YAHOO.widget.DataTable(
                    POLAR.View.getElementByClassName('pl-lookup-datatable', thisCopy._rootEle),
                    thisCopy._lookupPanelData.columnDefinitions,
                    thisCopy.dataSource,
                    { paginator: POLAR.View.DataTable.createDefaultPaginator() }
                );
                //set with on first and second colon for beter visula efect - TODO: set only for this lookup not all                
                //$('.pl-lookup-datatable' + ' table colgroup col:lt(2)').css('width', '10px');
                $('.pl-lookup-datatable').each(
                    function(i) {
                        $(this).find("table colgroup col:lt(2)").css('width', '10px');
                    }
                );

            }
        });

        panel.render();
        panel.show();
        var resize = new YAHOO.util.Resize(POLAR.View.getElementByClassName('pl-lookup-panel', this._rootEle), {
            autoRatio: true,
            handles: ['br', 'b'], //proxy: true, status: true,
            minWidth: 300,
            minHeight: 200

        });

        // setup resize handler to update the size of the Panel's body element whenever the size of the 'resizablepanel' DIV changes
        resize.on('resize', function(args) {
            var panelHeight = args.height;
            var headerHeight = null == this.header ? 0 : this.header.offsetHeight; // Content + Padding + Border
            var footerHeight = null == this.footer ? 0 : this.footer.offsetHeight; // Content + Padding + Border
            var bodyHeight = (panelHeight - headerHeight - footerHeight);
            var bodyContentHeight = (IE_QUIRKS) ? bodyHeight : bodyHeight - PANEL_BODY_PADDING;
            YAHOO.util.Dom.setStyle(this.body, 'height', bodyContentHeight + 'px');
            if (IE_SYNC) {
                // Keep the underlay and iframe size in sync. You could also set the width property, to achieve the same results, if you wanted to keep the panel's internal width property in sync with the DOM width.
                this.sizeUnderlay();
                // Syncing the iframe can be expensive. Disable iframe if you don't need it.
                this.syncIframe();
            }
        },
        panel, true);
        YAHOO.util.Event.on(POLAR.View.getElementByClassName('pl-lookup-panel-show', this._rootEle), 'click', panel.show, panel, true);
    };

    //call methods in contructor
    var idtmp2 = $("#" + this._idAutoCompleteLookup + " .pl-lookup-panel-show");
    $(idtmp2).click(function(event) {
        that._lookupPanel();
    });

    if (this._customAutoComplete) {
        //alert("stari kod za autocomplete, promijeni ga u novi");
        this._customAutoComplete();
    }
    else {
        var ds = new YAHOO.util.XHRDataSource(this._url);
        ds.responseSchema.resultsList = "Items";
        ds.responseSchema.fields = this._autoCompleteData.schema;
        ds.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
        ds.maxCacheEntries = 0; // dont chache results because we will dinamically change the source url       
        this._autocompleteXHRDataSource = ds;

        var ac = new YAHOO.widget.AutoComplete(POLAR.View.getElementByClassName('pl-autocomplete-input', this._rootEle), POLAR.View.getElementByClassName('pl-autocomplete-container', this._rootEle), ds);
        ac.prehighlightClassName = "yui-ac-prehighlight";
        ac.useShadow = false;
        ac.maxResultsDisplayed = 30;
        ac.useIFrame = true;
        ac.forceSelection = true;

        var thisCopy = this;
        ac.generateRequest = function(sQuery) {
            return thisCopy._autoCompleteData.query.replace('{0}', sQuery);
        };

        ac.formatResult = function(aResultItem, sQuery, sResultMatch) {
            var markup = [
                aResultItem[0], ', ',
                aResultItem[1], ', ',
                aResultItem[2], ', ',
                aResultItem[3], ', ',
                aResultItem[4], ', '
            ];
            return markup.join('');
        };

        ac.itemSelectEvent.subscribe(function(sType, aArgs) {
            var id;
            var url;

            var aData = aArgs[2];
            for (var i = 0; i < thisCopy._autoCompleteData.schema.length; i++) {
                if (thisCopy._autoCompleteData.schema[i] == thisCopy._propertyIdName) {
                    id = aData[i].toString();
                } else if (thisCopy._autoCompleteData.schema[i] == "URI") {
                    url = aData[i].toString();
                }
            }

            thisCopy._changeOnLinkedControl(id, url);
        });
    }

    if (this._customDataTable) {
        //alert("stari kod za customDataTable, promijeni ga u novi");
        this._dataTable = this._customDataTable();
    }
    else {
        if (this._dataTableData) {
            var dataSource = new YAHOO.util.DataSource(this._resourceHolder);
            dataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
            dataSource.responseSchema = {
                resultsList: this._dataTableData.resourceName,
                fields: this._dataTableData.fields
            };
            
            var self = this;
            var formatRemoveRow = function(elCell, oRecord, oColumn, oData) {
                var link = document.createElement("div");
                link.className = 'remove';
                elCell.appendChild(link);

                YAHOO.util.Event.addListener(link, 'click', function(e) {
                    dataTable.deleteRow(oRecord);
                    self._onRemove(oRecord.getData(this._propertyIdName));
                });                
            };

            this._dataTableData.columnDefinitions[0].formatter = formatRemoveRow;
            var element = YAHOO.util.Dom.get(this._dataTableData.resourceName);
            var dataTable = new YAHOO.widget.DataTable(element, this._dataTableData.columnDefinitions, dataSource);
            if (YAHOO.lang.isString(element)) {
                YAHOO.util.Dom.get(element).containedObject = dataTable;
            }
            else {
                element.containedObject = dataTable;
            }
            POLAR.View.setDataTableRowReader(element, function(recordData) {
                var data = new Object();
                data['ID'] = recordData['ID'];
                return data;
            });

            this._dataTable = dataTable;

            //set with on first and second colon for beter visula efect
            $("#" + this._dataTableData.resourceName + " table colgroup col:lt(2)").css('width', '10px');
        }
    }
}
//---------------------------------------------------------------------------------------------
POLAR.Widget.AutoCompleteLookup.dataTableFormatUrl = function(elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = '<a href="' + oRecord.getData('URL') + '">' + sData + '</a>';
};

//---------------------------------------------------------------------------------------------
POLAR.View.LookupPanel = function() { };
//---------------------------------------------------------------------------------------------
POLAR.Widget.AutoCompleteLookup.changeContact = function(newSubResource, recall) {
	if (!resource.Contact.Accounts && resource.Contact.ID != 0 && !recall)
	{
		POLAR.View.asyncGet(BASE_URL + "api/contact/" + resource.Contact.ID, function(contact) 
		{
			resource.Contact = contact;
			
			if(!newSubResource.Accounts && newSubResource.ID != 0)
			{
				newSubResource = contact;
			}
			
			POLAR.Widget.AutoCompleteLookup.changeContact(newSubResource, true);
        });
	}
	else
	{
		if (resource.Contact.Accounts && newSubResource) {
			var thisCopy = this;
			var accountsElement = YAHOO.util.Dom.get('Account.ID');
			while (accountsElement.options.length) {
				accountsElement.options[0] = null;
			}

			thisCopy.onRemove = function() {
				while (accountsElement.options.length) {
					accountsElement.options[0] = null;
				}
			};

			accountsElement.options.add(new Option('', 0));
			var originalAccountIndex = -1;
			for (var n = 0; n < resource.Contact.Accounts.length; n++) {
				accountsElement.options.add(new Option(newSubResource.Accounts[n].Name, newSubResource.Accounts[n].ID));

				if (newSubResource.Accounts[n].ID == resource.AccountFromTemplate.ID) {
					originalAccountIndex = n;
				}
			}
			
			if(-1 == originalAccountIndex) {
				for (var n = 0; n < resource.Contact.Accounts.length; n++) {

					if (newSubResource.PrimaryAccountID == newSubResource.Accounts[n].ID) {
						originalAccountIndex = n;
					}
				}
			}
			
			if(-1 == originalAccountIndex) {
				originalAccountIndex = 0;
			}
			
			if (1 < accountsElement.options.length) {
				accountsElement.options[0] = null;
				resource.Account = newSubResource.Accounts[originalAccountIndex];
				accountsElement.selectedIndex = originalAccountIndex;
			}
			else {
				resource.Account = null;
			}

			$("#Account\\.ID").change();//SP:invoke for refresh styled combobox        
			POLAR.View.Page.updateServiceLevelManagementFields();
		}
		else {
			var accountsElement = YAHOO.util.Dom.get('Account.ID');
			while (accountsElement.options.length) {
				accountsElement.options[0] = null;
			}
	        
			var url = BASE_URL + "api/accounts";
			
			POLAR.View.asyncGet(url, function(accounts) {
				$("#Account\\.ID").append(new Option("",0));
				
				$.each(accounts.Items, function (key, val) {
					$("#Account\\.ID").append(new Option(val.Name,val.ID));
				});
			});
		}
	}
}

//---------------------------------------------------------------------------------------------
//Order in this array matching visual order in web browser.
//---------------------------------------------------------------------------------------------
POLAR.View.SchemaNewResourceCreator = [
    {
        URN: "incident/template/{ID}"
    },
    {
        URN: "incidentcontact/template/{ID}"
    },
    {
        URN: "workorder/template/{ID}"
    },
    {
        URN: "user/template/{ID}"
    },
    {
        URN: "contact/template/{ID}"
    },
    {
        URN: "team/template/{ID}"
    },
    {
        URN: "account/template/{ID}"
    },
    {
        URN: "documentedit/namespace/{NamespaceID}/template/{TemplateID}"
    },
    {
        URN: "admin",
        /*OverwriteLabel: "Adddd", //overwrite label used when we want overwrite label tekst sent from server with JSON*/
        submenu: {
            itemdata: [
            { URN: "incidenttemplate" },
            { URN: "workordertemplate" },
            { URN: "contacttemplate" },
            { URN: "usertemplate" },
            { URN: "teamtemplate" },
            { URN: "accounttemplate" },
            { URN: "documenttemplate" },
            { URN: "emailtemplate" },
            { URN: "namespace" },
            { URN: "reportedit" },            
            { URN: "role" },
            { URN: "service" },
            { URN: "servicelevel" },
            { URN: "servicelevelagreement" },            
            { URN: "language" },            
            { URN: "emailnotification" },            
            { URN: "emailaccount" },
            { URN: "closureclassification" },
            { URN: "origin" },            
            { URN: "category" },
            { URN: "activedirectoryimportschema" }
            ]
        }
    }
];


//---------------------------------------------------------------------------------------------
POLAR.View.CreateMenuNewResource = function() {
    // sada vrtimo s obizrom koliko imamo elemenata u POLAR.View.NewResourceCreatorItems da toliko menija kreiramo.    
    var SameURNFinder = function(newResourceCreatorItem, schemaNewResourceCreatorItem) {
        if (schemaNewResourceCreatorItem.URN == newResourceCreatorItem.URN) {
            if (newResourceCreatorItem.GET == true) {
                return newResourceCreatorItem;
            }
        }
        return 0;
    }
    //----------------------------------------------------------------------------
    //??trebamo za pojedini sumbeni item ispitati je li ovaj trenutni user ima pravo GET metode a to dobivamo iz liste _resRep i ako ima onda ga dodajemo u listu
    //s  - is sumbenu list which we create here after find firs element
    //schemaNewResourceCreatorSubmenuItem - je elemenata array schemaNewResourceCreatorItem.submenu.itemdata
    function NewResourceCreatorSubmenuReducer(s, schemaNewResourceCreatorSubmenuItem) {
        if (typeof (s) === "undefined") {
            s = new Array();
        }
        if (s == 0 || s == null) {
            s = new Array();
        }
        //find which URN form schemaNewResourceCreatorSubmenuItem equivalent URN in JSON and return JSON element
        //var newResourceCreatorItem = POLAR.Util.Find(SameURNFinder, UserResourcePermissions.NewResourceCreators, schemaNewResourceCreatorSubmenuItem);
        var newResourceCreatorItem = POLAR.Util.Find(SameURNFinder, UserResourcePermissions.NewResourceCreators, schemaNewResourceCreatorSubmenuItem);
        if (newResourceCreatorItem != 0) {
            s.push({ text: newResourceCreatorItem.Label, url: newResourceCreatorItem.URL });
        }
        return s;
    }
    //----------------------------------------------------------------------------
    //svaki elemenat liste UserResourcePermissions.UserDefineResorucePermissions trazimo je li se moze mapirati na posalti URI Template
    //s - array u koji slazemo objekte tipa permissionItem iz liste UserResourcePermissions.UserDefineResorucePermissions
    //resorucePermissionsItem - je elemenat iz liste UserResourcePermissions.UserDefineResorucePermissions
    //navigationSubmenuUriTemplateItem - je URI template iz navigationItems.submenu.itemdata
    //return - ako za ovaj navigationItem imao pravo ga prikazati vracamo resorucePermissionsItem koji smo nasli u pretrazi i s time se prekida traznje a ako ne onda vracamo 0 i nastavlja se trazenje.
    function ExpandUriTemplateFromUserDefineResourceReducer(s, resorucePermissionsItem, navigationSubmenuUriTemplateItem) {
        if (s == 0 || s == null || s == undefined) {
            s = new Array();
        }
        //if is also URI template skip it.
        if (resorucePermissionsItem.URN.indexOf('{') != -1) {
            return s;
        }
        var flagMapping = POLAR.View.GetMappingResult(resorucePermissionsItem.URN, navigationSubmenuUriTemplateItem.URN);
        if (flagMapping == true) {
            if (resorucePermissionsItem.GET == true) {
                s.push({ text: resorucePermissionsItem.Label, url: resorucePermissionsItem.URL });
            }
        }
        return s;
    }
    //----------------------------------------------------------------------------
    function UriTempalteSameFinder(templateResorucePermissionsItem, navigationItem) {
        if (navigationItem.URN == templateResorucePermissionsItem.URN) {
            return templateResorucePermissionsItem;
        }
        else {
            return 0;
        }
    }
    var idsumbenu = 1;
    //----------------------------------------------------------------------------
    function CreateMenuItem(submenuItems, schemaNewResourceCreatorItem, newResourceCreatorItem) {
        if (submenuItems.length == 0) {
            return null;
        }

        if (submenuItems.length == 1 && schemaNewResourceCreatorItem.URN != 'admin') {
            var menuItem = [{ text: newResourceCreatorItem.Label, url: submenuItems[0].url}];
            return menuItem;
        }
        else {
            var localLabel = "";
            if (undefined == schemaNewResourceCreatorItem.OverwriteLabel) {
                localLabel = newResourceCreatorItem.Label;
            }
            else {
                localLabel = schemaNewResourceCreatorItem.OverwriteLabel;
            }
            var menuItem = [{ text: localLabel, url: ""}];
            menuItem[0].submenu = {};
            menuItem[0].submenu.itemdata = submenuItems;
            menuItem[0].submenu.id = "submenu" + idsumbenu.toString();
            idsumbenu = idsumbenu + 1;
            return menuItem;
        }
    }
    //----------------------------------------------------------------------------
    //For ever item find equivalent (same URN) in JSON i.e. UserResourcePermissions.NewResourceCreators create new menu item or also submenu.
    //schemaNewResourceCreatorItem - is element of POLAR.View.NewResourceCreatorItems
    var NewResourceCreatorMapper = function(schemaNewResourceCreatorItem) {
        //ispitivamo je li ovo URI Template, ako jeste odna na prvom nivou samo kreiramo root menu i trazimo sve URI koji se mogu mapirati na ovaj URI template
        var start = schemaNewResourceCreatorItem.URN.indexOf('{'); //find is it URI Template -
        if (start != -1) {
            //prvo potrazimo ima li ili ne ovakav URI Template. Nije nam vazno imao li GET ili ne pravo (cak i nebi smjeli imati jer je to onda znak da je nekto glupo podesio permissione
            //pa bi cak mogli to preskociti ako takvo se dogodi.. treba to vidjei je li se slaze sa svim URI tempaltima kao sto je to slucaj sa incidents/tempalte/{ID}
            //var newResourceCreatorItem = POLAR.Util.Find(UriTempalteSameFinder, UserResourcePermissions.NewResourceCreators, schemaNewResourceCreatorItem);
            var newResourceCreatorItem = POLAR.Util.Find(UriTempalteSameFinder, UserResourcePermissions.NewResourceCreators, schemaNewResourceCreatorItem);
            if (newResourceCreatorItem != 0) {
                //sad expadiramo sumbenu tj.. potrazimo sve URI koji se machirajuna ovaj URI Tempalte i od toga napravimo sumbenu array
                //var items = POLAR.Util.ReduceExt(ExpandUriTemplateFromUserDefineResourceReducer, UserResourcePermissions.NewResourceCreators, 0, schemaNewResourceCreatorItem);
                var items = POLAR.Util.ReduceExt(ExpandUriTemplateFromUserDefineResourceReducer, UserResourcePermissions.NewResourceCreators, 0, schemaNewResourceCreatorItem);
                //sad imao sve sumbenije
                var menuItem = CreateMenuItem(items, schemaNewResourceCreatorItem, newResourceCreatorItem);
                if (menuItem != null) {
                    oMenu.addItems(menuItem);
                }
                return schemaNewResourceCreatorItem; //MUST return same array member if we do not modified origina array
            }
        }
        //find which URN form schemaNewResourceCreatorItem equivalent URN in JSON and return JSON element
        //var newResourceCreatorItem = POLAR.Util.Find(SameURNFinder, UserResourcePermissions.NewResourceCreators, schemaNewResourceCreatorItem);
        var newResourceCreatorItem = POLAR.Util.Find(SameURNFinder, UserResourcePermissions.NewResourceCreators, schemaNewResourceCreatorItem);
        if (newResourceCreatorItem == 0) {
            return schemaNewResourceCreatorItem; //MUST return same array member if we do not modified origina array
        }
        else {
            //check for sumbenu items - ako imamo sumbenu odna treba izgenerirati pod menu i u navigaciji
            //if (typeof (schemaNewResourceCreatorItem.submenu.itemdata) !== "undefined") {
            if (typeof (schemaNewResourceCreatorItem.submenu.itemdata) !== "undefined") {
                //sada trebamo vrtjeti dodavanje u sumbenu
                var items = POLAR.Util.Reduce(NewResourceCreatorSubmenuReducer, schemaNewResourceCreatorItem.submenu.itemdata, 0);
                if (items != 0) {
                    var menuItem = CreateMenuItem(items, schemaNewResourceCreatorItem, newResourceCreatorItem);
                    if (menuItem != null) {
                        oMenu.addItems(menuItem);
                    }
                    return schemaNewResourceCreatorItem; //MUST return same array member if we do not modified origina array
                }
            }
            if (newResourceCreatorItem.URL != "") {//BR: if URL is not exist and if we do not submenu than do not create this menu item
                var menuItem = [{ text: newResourceCreatorItem.Label, url: newResourceCreatorItem.URL}];
                oMenu.addItems(menuItem);
            }
            return schemaNewResourceCreatorItem; //MUST return same array member if we do not modified origina array
        }
    }
    //----------------------------------------------------------------------------
    if (typeof (resource) === "undefined") {
        return;
    }
    
    //if (typeof (UserResourcePermissions) !== "undefined") {
    if (typeof (UserResourcePermissions) !== "undefined") {
        //var oMenuBar = new YAHOO.widget.MenuBar("mymenubar2", { lazyload: true });
        var oMenu = new YAHOO.widget.Menu("basicmenu", { position: "dynamic", showdelay: 0,  submenuhidedelay: 0, lazyload: true, iframe:false });
        //Position the bottom-left corner of the root menu to the 	        top-left corner of the "Yahoo!" anchor element.
        ///OLD version//oMenu.cfg.setProperty("context", ["rendertarget", "tl", "bl"]); //"tl"-menu, "bl"-target - oMenu.cfg.setProperty("context", ["rendertarget", "bl", "tl"]);
        POLAR.Util.Map(NewResourceCreatorMapper, POLAR.View.SchemaNewResourceCreator);
        ///OLD version//oMenu.render("rendertarget");
        ///OLD version//YAHOO.util.Event.addListener("menutoggle", "click", oMenu.show, null, oMenu);
        //--------------------------------------------------
        var menuItems = oMenu.getItems();

        function isEmpty(ob) {
            for (var i in ob) {
                return false; 
            }
            return true;
        }

        if (isEmpty(menuItems)) {
            $("#menutoggle").attr("disabled", "disabled");
        }

        var oMenuToggleButton = new YAHOO.widget.Button("menutoggle", { type: "menu", lazyloadmenu: true,  menu: menuItems });
    }
    else {
        return;
    }
    //Instantiate a Menu: The first argument passed to the constructor is the id for the Menu element to be created, the second is an object literal of configuration properties.
    //Add items to the Menu instance by passing an array of object literals     (each of which represents a set of YAHOO.widget.MenuItem     configuration properties) to the "addItems" method.
    //oMenu.addItems(aItems);
    //oMenu.addItems(aItems2);
    //    Since this Menu instance is built completely from script, call the     "render" method passing in the DOM element that it should be     appended to.
};
//---------------------------------------------------------------------------------------------
POLAR.View.CreateMenuNewResource();
//---------------------------------------------------------------------------------------------
//Main function for initalisation for everey page
//---------------------------------------------------------------------------------------------
POLAR.View.InitPage = function() {
    if (typeof (resource) === "undefined") {
        $('#myProfile').append("typeof (resource) === undefined");
    }
    else {
        if (typeof (AuthenticatedPerson) === "undefined") {
            $('#myProfile').append("typeof (resource) === undefined");
        }
        else {
            //Set My Profile  links 
            $("#myProfile").append("<a id='myProfileLink'></a> ");
            var url = "";
            if (AuthenticatedPerson.PersonType == "User" || AuthenticatedPerson.PersonType == "Administrator") {
                url = (UserResourcePermissions.VirtualUrl + "/user/" + AuthenticatedPerson.ID + "/view/full/iperson/" + AuthenticatedPerson.ID);
            }
            else if (AuthenticatedPerson.PersonType == "Contact") {
                url = (UserResourcePermissions.VirtualUrl + "/contact/" + AuthenticatedPerson.ID + "/view/full/iperson/" + AuthenticatedPerson.ID);
            }
            
            $("#myProfileLink").attr("href", url);
            $("#myProfileLink").text("My Profile");

            //Set Logout links
            $("#idLogout")
                .append($("<a>")
                    .attr("href", "#")
                    .text("Logout [" + AuthenticatedPerson.Name + "]")
                    .click(function() {
                        POLAR.View.asyncDelete(UserResourcePermissions.VirtualUrl + "/api/login", function() {
                            window.location = UserResourcePermissions.VirtualUrl + "/login";
                        });
           }));
        }
    }
};
//---------------------------------------------------------------------------------------------
POLAR.View.InitPage();
//---------------------------------------------------------------------------------------------
//Function evaluate (JS eval) JSON string from "Data" poperty  of inResorurce object to JS object and return repakage in resoruce representation object
//JS object resoruce representation which is a list of collection items in this items have Data property with JSON string.
//Used mostly in report to eval JSON string from "Data" poperty.
POLAR.View.evalDataInResourceRepresentation = function(inResourceRep) {
    if (inResourceRep.Items == undefined) {
        return inResourceRep;
    }

    for (var i = 0; i < inResourceRep.Items.length; i++) {
        try {
            inResourceRep.Items[i].Data = eval('(' + inResourceRep.Items[i].Data + ')');
        }
        catch (exception) { // skip invalide evalued data
            inResourceRep.Items[i].Data = "";
        }
    }
    return inResourceRep;
};
//---------------------------------------------------------------------------------------------
//defensive programing. If some report not have title.
//Used mostly in report to get something diferent then empty string 
POLAR.View.titleParser = function(Title) {
    if (Title == undefined || Title == "") {
        return "No Title";
    }
    else {
        return Title;
    }
};
//---------------------------------------------------------------------------------------------
//Determines whether or not the provided object is valida 
POLAR.View.IsValidObject = function() {
}

POLAR.View.PlaySound = function(soundObj) {
    var sound = document.getElementById(soundObj);
    sound.Play();
}

/*Random string 
Call with default charset [a-zA-Z0-9] or send in your own:
var randomValue = randomString(5);
var randomValue = randomString(5, 'PICKCHARSFROMTHISSET');
*/
POLAR.View.randomString = function(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
        var randomPoz = Math.floor(Math.random() * charSet.length);
        randomString += charSet.substring(randomPoz, randomPoz + 1);
    }
    return randomString;
}
//----------------------------------------------------
POLAR.View.setTitleAndResourceName = function(inLabel) {
    
    var id = "";
    var label = "";
    var capiton = "";

    if (!YAHOO.lang.isUndefined(inLabel) && !YAHOO.lang.isNull(inLabel)) {
        label = inLabel;
    }
    else {
        label = "";
    }
    $("#idResourceName").text(label);
    
    if (!YAHOO.lang.isUndefined(resource.Name) && !YAHOO.lang.isNull(resource.Name)) {
        capiton = resource.Name;
    }
    else {
        if (!YAHOO.lang.isUndefined(resource.Title) && !YAHOO.lang.isNull(resource.Title)) {
            capiton = resource.Title;
        }
        else {
            capiton = "";
        }
    }
    if (!YAHOO.lang.isUndefined(resource.ID) && !YAHOO.lang.isNull(resource.ID)) {
        id = resource.ID.toString();
    }
    var finalText = ""; //construct string "id-label-capiton
    if (id.length > 0) {
        finalText = id;
        if (label.length > 0) {
            finalText = finalText + '-' + label;
        }
        if (capiton.length > 0) {
            finalText = finalText + '-' + capiton;
        }
    }
    else {
        if (label.length > 0) {
            finalText = label;
            if (capiton.length > 0) {
                finalText = finalText + '-' + capiton;
            }
        }
        else {
            if (capiton.length > 0) {
                finalText = capiton;
            }
        }
    }
    $(this).attr("title", finalText);

}
//----------------------------------------------------
//Create button Category.. on form (incident, user,...)
//selectedArray - list of category from resource.Categories
//allItemsArray - list of all categories in aplication _categoryRepository.GetAll())
//categoryButtonId - ID in HTML structure: <button id="categoryButtonId" type="button"><%= CommonLabels.Category%>...</button>
POLAR.View.CategoryButton = function (selectedArray, allItemsArray, categoryButtonId) {
    var oCategory = new YAHOO.widget.Button(categoryButtonId);
    oCategory.on("click", function() {
		function alphabetical(a, b)
		{
			 var A = a.Name.toLowerCase();
			 var B = b.Name.toLowerCase();
			 if (A < B){
				return -1;
			 }else if (A > B){
			   return  1;
			 }else{
			   return 0;
			 }
		}
    
        $("#categoryButtonId").after("<div id='categoryMasterMenuID' class='psPopMenu' style='display:none' ></div>");
        var selectablePopUpMenuControl = new POLAR.View.SelectablePopUpMenuControl(resource.Categories.sort(alphabetical), categoriesAll.sort(alphabetical));
        var pos = $('#categoryButtonId').position();
        $("#categoryMasterMenuID").css(
            { position: "absolute",
                marginLeft: 0,
                marginTop: 0,
                top: pos.top + $("#categoryButtonId").height() + 2,
                left: pos.left + 2
            }
        );
        
        /* MK: ovo je uvijek false zbog checkMouse na mousedown
        if ($("#categoryMasterMenuID").is(':visible')) {
            $('#categoryMasterMenuID').empty();
            $('#categoryMasterMenuID').hide();
            return;
        }
        else {*/
            selectablePopUpMenuControl.renderSelectablePopUpMenu();
            $('#categoryMasterMenuID').show();
        //}

        var checkMouse = function(e) {
            //is the mouse inside a clickmenu? if yes, is it an open (the current) one?

            var clickedElement = $(e.target).parents("#categoryMasterMenuID");
            //if ($(e.target).parent("#categoryMasterMenuID").length > 0) {
            if (clickedElement.length == 0) {
                $('#categoryMasterMenuID').empty();
                $('#categoryMasterMenuID').hide();
                $(document).unbind('mousedown', checkMouse);              
            } 
        };

        $(document).bind('mousedown', checkMouse);
        //On press ESC key hide popupmenu
        /*var kl = new YAHOO.util.KeyListener(
                    document,
                    { keys: 27 },
                    { fn: panel.hide, scope: panel, correctScope: true }
                 );
                 
        panel.cfg.queueProperty("keylisteners", kl);*/
    });     
}
//----------------------------------------------------
POLAR.View.SelectablePopUpMenuControl = function(selectedArray, allItemsArray) {
    var that = this;

    function getCategoryFromAllItemsArray(id) {
        for (var i = 0; i < allItemsArray.length; i++) {
            if (id == allItemsArray[i].ID) {
                return allItemsArray[i];
            }
        }
    }

    //public method for rendering from strech this menu
    this.renderSelectablePopUpMenu = function() {    
        //TOOD: treba prvo ispsiati kategorije koje su selektirane a tek onda ostale.
        //create temp array , insert in it selected category and after that other from all category but not selected
        var selectedCategory = [];
        for (var i = 0; i < selectedArray.length; i++) {
            selectedCategory.push({ ID: selectedArray[i].ID, Name: selectedArray[i].Name });
        }

        $("#categoryMasterMenuID").append("<div id='categoryMenuID' class='psPopMenuContent'>");

        //render selected category
        for (var i = 0; i < selectedCategory.length; i++) {
            var id = "s" + POLAR.View.randomString(6);
            $("#categoryMenuID").append("<div id='" + i + "menuItem' class='psPopMenuItem'>" +
                "<input id='" + id + "' type='checkbox' checked='checked' value='" + selectedCategory[i].ID + "' />" +
                "<span> " + selectedCategory[i].Name + "</span>" + "<div>");

            $("#" + id + "").click(function(eventObject) {
                //find selected category and remove from selected list
                for (var k = 0; k < selectedArray.length; k++) {
                    if (eventObject.target.value == selectedArray[k].ID) {
                        //selectedArray.remove(k);                        
                        POLAR.Util.ArrayRemove(selectedArray, k);
                        $('#categoryMasterMenuID').empty();
                        that.renderSelectablePopUpMenu();
                        $('#categoryMasterMenuID').show();
                        break;
                    }
                }
            });
        }

        //add divider betwen selected and non selected 
        $("#categoryMenuID").append("<div class='psPopMenuBarItem'><div>");

        //find other not selected category
        var notSelectedCategory = [];
        for (var i = 0; i < allItemsArray.length; i++) {
            var idTmp = allItemsArray[i].ID;
            var find = false;
            for (var j = 0; j < selectedArray.length; j++) {
                if (idTmp == selectedArray[j].ID) {
                    find = true;
                    break;
                }
            }
            if (find == false) {
                notSelectedCategory.push({ ID: allItemsArray[i].ID, Name: allItemsArray[i].Name });
            }
        }

        //render NOT selected category
        for (var i = 0; i < notSelectedCategory.length; i++) {
            var id = "nos" + POLAR.View.randomString(6);
            $("#categoryMenuID").append("<div id='" + i + "menuItem' class='psPopMenuItem'>" +
                "<input id='" + id + "' type='checkbox'  value='" + notSelectedCategory[i].ID + "' />" +
                "<span> " + notSelectedCategory[i].Name + "</span>" + "<div>");
            $("#" + id + "").click(function(eventObject) {
                var idNonSelected = eventObject.target.value;
                var categoryObject = getCategoryFromAllItemsArray(idNonSelected);
                selectedArray.push({ ID: categoryObject.ID, Name: categoryObject.Name });
                $('#categoryMasterMenuID').empty();
                that.renderSelectablePopUpMenu();
                $('#categoryMasterMenuID').show();
            });
        }

        //append command
        $("#categoryMasterMenuID").append("<div class='psPopMenuBarItem'><div>");

        var authorization = new POLAR.Authorization();

        // check if we can create a category, display create new category link if so
        if (authorization.isCreateResourceAllowed('category')) {
            $("#categoryMasterMenuID").append("<div id='createNewCategory' class='psPopMenuItem'><a href=#> Create new category</a><div>");

            //event handler on create New Category command
            $('#createNewCategory').click(function(event) {
                event.preventDefault();
                if ($("#messageBoxDialog").dialog('isOpen') == true) {
                    $("#messageBoxDialog").dialog('close');
                }
                $("#messageBoxDialog").dialog('destroy');
                $.ui.dialog.defaults.bgiframe = true;
                $('#messageBoxDialog').empty();

                //success Handler on POST when create new category
                function successHandler(dataResponse) {
                    selectedArray.unshift(dataResponse);
                    allItemsArray.push(dataResponse);
                    $("#messageBoxDialog").dialog('close');
                    //POLAR.View.SelectablePopUpMenuControl(selectedArray, allItemsArray);
                    that.renderSelectablePopUpMenu();
                    //$('#categoryMasterMenuID').show();
                }

                //failure Handler on POST when try create new category
                function failureHandler(dataResponse) {
                    $("#messageBoxDialog #popupMessage").replaceWith("The category name you have chosen already exists. Please try another name:");
                }

                //Configuration for popup dialgo for creating new category 
                $("#messageBoxDialog").dialog({
                    bgiframe: true,
                    width: 450,
                    height: 200,
                    //modal: true,
                    buttons: {
                        Cancel: function() {
                            $(this).dialog('close');
                        },
                        OK: function() {
                            var jsData = {};
                            jsData.Name = $("#createNewCategoryEdit").val();
                            YAHOO.lang.JSON.useNativeStringify = false; //workarround for some IE8 bug in native browser converter to JSON string
                            var jsonData = YAHOO.lang.JSON.stringify(jsData);
                            var url = UserResourcePermissions.VirtualUrl + '/api/category';
                            POLAR.View.SilenceAJAX('POST', url, jsonData, successHandler, failureHandler);
                        }
                    }
                });
                $('#messageBoxDialog').dialog('open');
                $('#messageBoxDialog').append("<div id='popupMessage'> Please enter a new category name: <div/>");
                $('#messageBoxDialog').append("<input type='text' class='psTextbox' id='createNewCategoryEdit'/>");
            });
        }

        if (authorization.isGetResourceAllowed('categories')) {
            var url = UserResourcePermissions.VirtualUrl + "/categories";
            $("#categoryMasterMenuID").append("<div class='psPopMenuItem'><a href=" + url + ">Manage categories</a><div>");
        }
    }
}
//----------------------------------------------------
//Bookmarks Control
function BookmarkControl() {
    return; //SP:2009-12-05 - we do not use for now this component     
    
    var setNameOfResource = function(userpreferenceitem) {
        if (!YAHOO.lang.isUndefined(resource.Name) && !YAHOO.lang.isNull(resource.Name)) {
            userpreferenceitem.Name = resource.Name;
        }
        else {
            if (!YAHOO.lang.isUndefined(resource.Title) && !YAHOO.lang.isNull(resource.Title)) {
                userpreferenceitem.Name = resource.Title;
            }
            else {
                userpreferenceitem.Name = "Name";
            }
        }
        return userpreferenceitem;
    }   
    
    var inicializeDragableTitle = function() {
        //add json information to dragabletitle.
        var userpreferenceitem = {};
        userpreferenceitem = setNameOfResource(userpreferenceitem);
        userpreferenceitem.Date = new Date();
        userpreferenceitem.URL = resource.URL;
        var jsonStr = YAHOO.lang.JSON.stringify(userpreferenceitem);
        $("#sortablesource li").attr({ json: jsonStr });
        $("#sortablesource li").attr({ id: "dragabletitle" });
        $("#sortablesource li").text("");
    }
    inicializeDragableTitle();

    var that = this;
    //------------------------------------
    //napunimmo sortable lsitu
    //POLAR.View.asyncGet(UserResourcePermissions.VirtualUrl + '/api/reportedit/' + AuthenticatedPerson.ID,    
    var onResponseSuccess = function(response) {
        //BookmarkControl.prototype.onResponseSuccess = function() {
        var userpreference = POLAR.View.convertAsyncResponseToObject(response);
        if (!YAHOO.lang.isUndefined(userpreference) && !YAHOO.lang.isNull(userpreference) && YAHOO.lang.isObject(userpreference)) {
            resource.userpreference = userpreference;
            if (!YAHOO.lang.isUndefined(resource.userpreference.bookmarks) && !YAHOO.lang.isNull(resource.userpreference.bookmarks) && YAHOO.lang.isObject(resource.userpreference.bookmarks)) {
                if (!YAHOO.lang.isUndefined(resource.userpreference.bookmarks.list) && !YAHOO.lang.isNull(resource.userpreference.bookmarks.list) && YAHOO.lang.isArray(resource.userpreference.bookmarks.list)) {
                }
                else {
                    resource.userpreference.bookmarks.list = [];
                    resource.userpreference.bookmarks.modified = Date.today().add(-3650).days();
                }
            }
            else {
                resource.userpreference.bookmarks = {};
                resource.userpreference.bookmarks.list = [];
                resource.userpreference.bookmarks.modified = Date.today().add(-3650).days();
            }
        }
        else {
            resource.userpreference = {};
            resource.userpreference.bookmarks = {};
            resource.userpreference.bookmarks.list = [];
            resource.userpreference.bookmarks.modified = Date.today().add(-3650).days();
        }        
        that.initBookmarks();
    };


    var onResponseFailure = function(response) {
        resource.userpreference = {};
        resource.userpreference.bookmarks = {};
        resource.userpreference.bookmarks.list = {};
        resource.userpreference.bookmarks.modified = Date.today().add(-3650).days();
        that.initBookmarks();
    };
    
    
    /*Check is bookmark on storage newer than this in JavasScrip object and if it is a true reload form storage and update bookmark control
    This story usaly happen when some modified bookmark in other browser windows/tab */
    var checkAndUpdateBookmarkControl = function(delegate) {
        var onResponse1 = function(response) {
            try {
                //POLAR.View.PlaySound("sound1");
                var userpreference = POLAR.View.convertAsyncResponseToObject(response);
                var modified = POLAR.View.DateTime.stringToDate(userpreference.bookmarks.modified);
                //alert(modified.getTime().toString());
                var flag = false;
                if (YAHOO.lang.isObject(resource.userpreference.bookmarks.modified)) {
                    flag = resource.userpreference.bookmarks.modified.isBefore(modified);
                }
                else if (YAHOO.lang.isString(resource.userpreference.bookmarks.modified)) {
                    var modified2 = POLAR.View.DateTime.stringToDate(resource.userpreference.bookmarks.modified);
                    flag = modified2.isBefore(modified);
                }
                else {
                    return;  //some error
                }

                if (flag == true) {
                    //alert(modified.getTime().toString() + " - " + flag);
                    resource.userpreference.bookmarks = userpreference.bookmarks;
                    that.removeAllDomElementFromBookmarks();
                    that.initBookmarks();
                }
            }
            catch (e) {
            }

            if (!YAHOO.lang.isUndefined(delegate) && !YAHOO.lang.isNull(delegate) && YAHOO.lang.isFunction(delegate)) {
                delegate(); //execute no matter what  
            }
        }

        var localCallback2 = {
            success: onResponse1,
            failure: onResponse1
        };

        YAHOO.util.Connect.asyncRequest('GET', UserResourcePermissions.VirtualUrl + '/api/reportedit/' + AuthenticatedPerson.ID, localCallback2, '');
    }


    //Get sortable bookmark list from #sortablebookmarks and write to resource.userpreference.bookmarks
    var getBookmarks = function () {
        var result = $('#sortablebookmarks').sortable('toArray');
        if (result.length > 0) {
            for (var i = 0; i < result.length; i++) {
                try {
                    var jsonStr = $("#sortablebookmarks #" + result[i]).attr("json");
                    var userpreferenceitem = YAHOO.lang.JSON.parse(jsonStr);
                    resource.userpreference.bookmarks.list.push(userpreferenceitem);
                }
                catch (e) {
                }
            }
        }
    };

    /*Helper class for $("#sortablebookmarks").sortable({ update: function(event, ui) -  */
    var updateAndSaveBookmarkResource = function () {
        //delete all bookmarsk from resource.userpreference.bookmarks and over getBookmarks(); ad in resource form bookmark kontrol
        resource.userpreference.bookmarks.list.remove(0, -1);
        getBookmarks();
        resource.userpreference.bookmarks.modified = new Date();
        var transaction = YAHOO.util.Connect.asyncRequest('POST', UserResourcePermissions.VirtualUrl + '/api/reportedit', POLAR.View.requestCallbackAJAXSilence, YAHOO.lang.JSON.stringify(resource.userpreference));

        //change new element if dragable
        var jsonStr = $("#sortablebookmarks #dragabletitle").attr("json");
        if (!YAHOO.lang.isUndefined(jsonStr) && !YAHOO.lang.isNull(jsonStr)) {//this hapen oanly when we add new element
            $("#sortablebookmarks #dragabletitle").text("");
            var item = YAHOO.lang.JSON.parse(jsonStr);
            $("#sortablebookmarks #dragabletitle").append("<a class='bookmarkitem' href=" + item.URL + "> " + item.Name + "</a></li>");
            $("#sortablebookmarks #dragabletitle").removeClass('draghandler2');
            $("#sortablebookmarks #dragabletitle").removeClass('draghandler1');
        }
        //after all change id of dragabletitle to some random title
        $("#sortablebookmarks #dragabletitle").attr("id", POLAR.View.randomString(10));
    }

    var addDeleteIcon = function () {
        $("#sortablebookmarks li").each(function(i) {
            $("#" + this.id).prepend("<span id='" + i + "bkmdel' class='removebookmarkitem'> </span>");
            $("#" + i + "bkmdel").click(function(eventObject) {
                $(this).parent().remove();
                updateAndSaveBookmarkResource();
            });
        });
    }

    var removeDeleteIcon = function () {
        $("#sortablebookmarks li").each(function(i) {
            $("#" + this.id + " span").remove();
        });
    }

    $(".bookmarkmoreinfo").toggle(
        function() {
            checkAndUpdateBookmarkControl(addDeleteIcon);//addDeleteIcon();
        },
        function() {
            checkAndUpdateBookmarkControl(removeDeleteIcon);//removeDeleteIcon();
        }
    );

    //------------------------------------
    /*Main inicialization all element of bookmark control form resource.userpreference.bookmarks*/
    //BookmarkControl.prototype.initBookmarks = function(that) {
    //var initBookmarks = function() {
    this.initBookmarks = function() {
        //Fill sortable bookmark list #sortablebookmarks from resource.userpreference.bookmarks
        function postBookmarks() {
            try {
                resource.userpreference.bookmarks.list = that.makeBookmarksListUnique(resource.userpreference.bookmarks.list);
                for (var i = 0; i < resource.userpreference.bookmarks.list.length; i++) {
                    var item = resource.userpreference.bookmarks.list[i];
                    if (item) {
                        var jsonStr = YAHOO.lang.JSON.stringify(item);
                        $("#sortablebookmarks").append("<li id='" + i + "bkmitem' json='" + jsonStr + "'> <a class='bookmarkitem' href=" + item.URL + "> " + item.Name + "</a></li>");
                        //$("#sortablebookmarks").append("<li id='" + i + "bkmitem' json='" + jsonStr + "'> <span id='" + i + "bkmdel' class='removebookmarkitem'> </span> <a class='bookmarkitem' href=" + item.URL + "> " + item.Name + "</a></li>");	                            
                    }
                }
                resource.userpreference.bookmarks.modified = new Date();
            }
            catch (e) {
                resource.userpreference.bookmarks = {};
                resource.userpreference.bookmarks.list = [];
                resource.userpreference.bookmarks.modified = Date.today().add(-3650).days();
            }
        }
        postBookmarks();

        $("#sortablesource").sortable({
            connectWith: '#sortablebookmarks',
            /*forceHelperSize: true,*/
            start: function(event, ui) {//todo kad se pocne vuci elemenata
                $("#sortablesource #dragabletitle").append("<div class='draghandler2'> </div>");                
                checkAndUpdateBookmarkControl();
            },
            sort: function(event, ui) {
            },
            stop: function(event, ui) {//todo  promijneit stil kad se kreira ponovo  ili kad se prestane vocu ebz obzirai jesmo gli ga narpavili                
                $("#sortablesource #dragabletitle div").remove();                
                $("#sortablesource #dragabletitle").addClass('draghandler1');
            },

            update: function(event, ui) {
                //iz dragable se mice zadnji elemenat pa ga moramo obnoviti.
                var result = $('#sortablesource').sortable('toArray');
                if (result.length >= 0) {//ako je 
                    $("#sortablesource").append("<li></li>");
                    var userpreferenceitem = {};
                    userpreferenceitem = setNameOfResource(userpreferenceitem);
                    userpreferenceitem.Date = new Date();
                    userpreferenceitem.URL = resource.URL;
                    var jsonStr = YAHOO.lang.JSON.stringify(userpreferenceitem);
                    $("#sortablesource li").attr({ json: jsonStr });
                    $("#sortablesource li").attr({ id: "dragabletitle" });
                    $("#sortablesource li").text("");
                }
            }
        }).disableSelection();

        $("#sortablebookmarks").sortable({
            connectWith: '#bookmarkdelete',            
            placeholder: 'ui-state-highlight',
            receive: function(event, ui) {//ovdje ui.item i ui.sender pokazuju na dragable elemenata 
                //$(ui.sender).sortable('cancel'); //vracamo prenoseni item takod aga nemoramo ponov rekreirati na pocetnom mejstu a ovdje smo dobili sve potrebne podatek                         
            },
            update: function(event, ui) {//ovdje ui.item pokazuju na novostvoreni elemenata u sortable listi ALI ovo se dogadja i kada samo mijesamo elemente liste

                //ako u listiima iti jedna sa IDoma #dragabletitle to znaci da upravo dodajmo sa dragable jedan tag
                //check is duplicate when add #dragabletitleand - if not, save, or delete from sortable list and DO NOT save                        
                if ($("#sortablebookmarks #dragabletitle").length > 0) {
                    var jsonStr0 = $("#sortablebookmarks #dragabletitle").attr("json");
                    if (!YAHOO.lang.isUndefined(jsonStr0) && !YAHOO.lang.isNull(jsonStr0)) {//this need hapen only when we add new element                                                      
                        var bookmarksFromControl = $('#sortablebookmarks').sortable('toArray');
                        if (bookmarksFromControl.length > 1) {
                            //remove duplicate items
                            var item0 = YAHOO.lang.JSON.parse(jsonStr0);
                            for (var i = 0; i < bookmarksFromControl.length; i++) {
                                try {
                                    var jsonStrX = $("#sortablebookmarks #" + bookmarksFromControl[i]).attr("json");
                                    var itemX = YAHOO.lang.JSON.parse(jsonStrX);
                                    if ((itemX.URL == item0.URL) && (bookmarksFromControl[i] != "dragabletitle")) {
                                        $("#sortablebookmarks #dragabletitle").remove();
                                        return;
                                    }
                                }
                                catch (e) {
                                    //POLAR.View.PlaySound("sound1");
                                }
                            }
                        }
                        else {
                            //return; //??? some error 
                        }
                    }
                    else {//if do not have json, we need delete it - some error?
                        $("#sortablebookmarks #dragabletitle").remove();
                    }
                }
                updateAndSaveBookmarkResource();                
            }
        }).disableSelection();
        //}); //end AJAX GET request.
    };
  
    var localCallback = {
        success: onResponseSuccess,
        failure: onResponseFailure
    };
    
    YAHOO.util.Connect.asyncRequest('GET', UserResourcePermissions.VirtualUrl + '/api/reportedit/' + AuthenticatedPerson.ID, localCallback, '');
}
//------------------------------------
//make bookmarks.list unique against URL
//var makeBookmarksListUnique = function(bookmarkList) {
//------------------------------------
BookmarkControl.prototype.makeBookmarksListUnique = function(bookmarkList) {
    var newList = [];
    var objectTemp = {};
    var counter = 0;
    for (var i = 0; i < bookmarkList.length; i++) {
        //preskoci dodavanje tako da nam ostane u listi onaj elemenat koji je bio prviji
        if (YAHOO.lang.isUndefined(objectTemp[bookmarkList[i].URL]) == true) {
            objectTemp[bookmarkList[i].URL] = bookmarkList[i];
            newList.push(objectTemp[bookmarkList[i].URL]);
        }
    }
    return newList;
}
//------------------------------------
/*Remove all DOM element form BookmarkControl*/
BookmarkControl.prototype.removeAllDomElementFromBookmarks = function() {
    $("#sortablebookmarks").children().each(function(i) {
        //alert(this.id);
        //$("#" + this.id).remove();
        $(this).remove();
    });
}

//---------------------------------------------------------------------------------------------
function PersonPreferenceHelper(resRep) {
    //TODO:SP:009-12-07 mozda i nebi trebli unutar resRep dodavati ovaj ExtendData.PersonPreference.Data vec jednostanvo PersonPreference koristi kao i svaki drugi resoruce kojega dohvatimo preko AJAXa    
    try {
        if (YAHOO.lang.isUndefined(resRep)) {
            return;
        }

        var constructIfNotExistPersonPreference = function() {
            //if do not exist organization of data in PersonPreference object then we need contruct it here.
            if (YAHOO.lang.isUndefined(resRep.ExtendData.PersonPreference.Data)) {
                resRep.ExtendData.PersonPreference.Data = {};
                if (YAHOO.lang.isUndefined(resRep.ExtendData.PersonPreference.Data.RecentItems)) {
                    resRep.ExtendData.PersonPreference.Data.RecentItems = [];
                }
            }
            else {
                if (YAHOO.lang.isUndefined(resRep.ExtendData.PersonPreference.Data.RecentItems)) {
                    resRep.ExtendData.PersonPreference.Data.RecentItems = [];
                }
            }
        }

        var attachPersonPreferenceToResRep = function(inPersonPreference) {
            if (YAHOO.lang.isUndefined(inPersonPreference)) {
                return;
            }
            if (YAHOO.lang.isUndefined(resRep.ExtendData)) {
                resRep.ExtendData = {};
            }
            resRep.ExtendData.PersonPreference = inPersonPreference;
            constructIfNotExistPersonPreference();

        }

        var createRecentItem = function() {
            //now we have resRep.ExtendData.PersonPreference.Data.RecentItems, add new entry in this list RecentItems
            var recentItem = new Object();
            var url = window.location.href;
            recentItem.URL = url.substring(BASE_URL.length, url.length);
            recentItem.Created = new Date();
            return recentItem;
        }

        var showRecentItmes = function() {
            var strUserRecentItems = "";
            var recentItems = resRep.ExtendData.PersonPreference.Data.RecentItems;
            for (var i = 0; i < recentItems.length; i++) {
                if (!YAHOO.lang.isNull(recentItems[i])) {
                    if (!YAHOO.lang.isNull(recentItems[i].URL)) {
                        var url = recentItems[i].URL.toString();

                        var uri = url.toLowerCase();
                        //cut  virtual part of URL
                        var index = uri.indexOf("?");
                        if (index != -1) {
                            uri = uri.substring(0, index);
                        }                        
                        uri = uri.substring(0, 20);
                        //strUserRecentItems = strUserRecentItems + "<span class='item_selected'> <a class='recentItem' href='" + url + "'>" + uri + "</a></span>"; /*+ resource.UserPreference.UserRecentItems[i].CreatedOn*/
                        //2010-05-18 - strUserRecentItems = strUserRecentItems + "<span class='item_selected'> <a class='recentItem' href='" + url + "'>" + uri + "</a></span>"; /*+ resource.UserPreference.UserRecentItems[i].CreatedOn*/
                        strUserRecentItems = strUserRecentItems + "<span class='recentListItem'> <a href='" + BASE_URL + url + "'>" + uri + "</a></span>" + "<br />";                        
                    }
                }
            }
            $("#IdUserPreference").empty();
            $("#IdUserPreference").append(strUserRecentItems);
        }


        var arrangeRecentList = function() {
            var numberOfItems = 10;
            resRep.ExtendData.PersonPreference.Data.RecentItems.unshift(createRecentItem());
            resRep.ExtendData.PersonPreference.Data.RecentItems = POLAR.Util.arrayUnique(resRep.ExtendData.PersonPreference.Data.RecentItems, "URL");
            if (resRep.ExtendData.PersonPreference.Data.RecentItems.length > numberOfItems) {
                resRep.ExtendData.PersonPreference.Data.RecentItems = resRep.ExtendData.PersonPreference.Data.RecentItems.slice(0, numberOfItems);
            }

        }

        this.initPersonPreference = function() {
			if (undefined !== AuthenticatedPerson) {
				function successHandler3(dataResponse) {
					attachPersonPreferenceToResRep(dataResponse);
					arrangeRecentList();
	                
					YAHOO.lang.JSON.useNativeParse = false;
					YAHOO.lang.JSON.useNativeStringify = false;
					var jsonData3 = YAHOO.lang.JSON.stringify(resRep.ExtendData.PersonPreference);
					var url = BASE_URL + 'api/personpreference/' + resRep.ExtendData.PersonPreference._doc + '/iperson/' + AuthenticatedPerson.ID;
					//because we add new recent item entity we need write to server this personpreference before leave this page.
					POLAR.View.SilenceAJAX('PUT', url, jsonData3, null, null);
					showRecentItmes();
				}

				function failureHandler2(dataResponse) {
					//najvjerojatni revision je zastario pa stoga uzimamo ponovo sa GET taj personpreference representation i probamo ponovo. ako i ponovo ne prodje idemo dalje.
					POLAR.View.SilenceAJAX('GET', BASE_URL + 'api/personpreference/' + resRep.ExtendData.PersonPreference._doc + '/iperson/' + AuthenticatedPerson.ID, null, successHandler3);
				}

				function successHandler1(dataResponse) {
					if (dataResponse == null) {
						return;
					}
					attachPersonPreferenceToResRep(dataResponse);
					arrangeRecentList();

					YAHOO.lang.JSON.useNativeParse = false; // Always use the JavaScript implementation for parsing
					YAHOO.lang.JSON.useNativeStringify = false; // Always use the JavaScript implementation for stringifying 
					var jsonData = YAHOO.lang.JSON.stringify(resRep.ExtendData.PersonPreference);
					var url = BASE_URL + 'api/personpreference/' + resRep.ExtendData.PersonPreference._doc + '/iperson/' + AuthenticatedPerson.ID;
					//because we add new recent item entity we need write to server this personpreference before leave this page.
					POLAR.View.SilenceAJAX('PUT', url, jsonData, null, failureHandler2);
					showRecentItmes();
				}

				//If we do not get personpreference data for this authenticatedperson then we need to create new over POST
				function failureHandler1(dataResponse) {
					var jsData = {};
					jsData.Data = {};
					jsData.Data.Type = "PersonPreference";
					jsData.Data.PersonID = AuthenticatedPerson.ID;
					jsData.Data.RecentItems = [];
					jsData.Data.RecentItems.unshift(createRecentItem());
					//jsData.Date = new Date();
					YAHOO.lang.JSON.useNativeStringify = false; //workarround for some IE8 bug in native browser converter to JSON string
					var jsonData = YAHOO.lang.JSON.stringify(jsData);
					var url = BASE_URL + 'api/personpreference/iperson/' + AuthenticatedPerson.ID;
					POLAR.View.SilenceAJAX('POST', url, jsonData, null, null);
				}

				if (!YAHOO.lang.isUndefined(AuthenticatedPerson.PersonPreferenceID) && !YAHOO.lang.isNull(AuthenticatedPerson.PersonPreferenceID) && AuthenticatedPerson.PersonPreferenceID.length > 0) {
					POLAR.View.SilenceAJAX('GET', BASE_URL + 'api/personpreference/' + AuthenticatedPerson.PersonPreferenceID + '/iperson/' + AuthenticatedPerson.ID, null, successHandler1, failureHandler1);
				}
				else {
					POLAR.View.SilenceAJAX('GET', BASE_URL + 'api/personpreference/0/iperson/' + AuthenticatedPerson.ID, null, successHandler1, failureHandler1);
				}
			}
        }
        this.initPersonPreference();
    }
    catch (e) { 
       
    }
    
    // IE8 does not support Array.indexOf, this is recommended way for defining it from mozzila development center:
    // https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function(elt /*, from*/) {
            var len = this.length >>> 0;

            var from = Number(arguments[1]) || 0;
            from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
            if (from < 0)
                from += len;

            for (; from < len; from++) {
                if (from in this &&
          this[from] === elt)
                    return from;
            }
            return -1;
        };
    }
}



/*JQuery plugin for styled select HTML element*/
(function($) {
    $.fn.jqTransform = function(options) {
        return this.each(function() {
            var $select = $(this);
            // Now add the html for the select
            var selectId = $select.attr("id").toString().replace(/\./g, ''); //SP: replace dot from  ID string because jquery can not manipulate correctly with dot char in name
            var spanSelectId = selectId + "selectstyled";
            var newText = $select.find("option:selected").text();

            var newWidth = 0;
            if ($select.hasClass("smallwidth") == true || $select.hasClass("middlewidth")) {
                newWidth = $select.width();
            }
            else {
                newWidth = $select.parent().width();
                //newWidth = $select.width();
            }
            
            $("#" + spanSelectId).remove();//if we call previouse this metthod .. we must destory span element from DOM.
            $select.before("<span id='" + spanSelectId.toString() + "' class='selectstyled' style='width:" + newWidth + "px;'>" + newText + "</span>");
            $select.unbind();
            $select.change(function() {
                var newText2 = $select.find("option:selected").text();
                $("#" + spanSelectId).text(newText2);
            });
            return;
        }); // End select each 
    }; // End the Plugin 
})(jQuery);
$("select.styled").jqTransform();


/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/

(function($) {
    $.fn.jqpHint = function(blurClass) {
        if (!blurClass) {
            blurClass = 'blur';
        }

        return this.each(function() {
            // get jQuery version of 'this'
            var $input = $(this),

            // capture the rest of the variable to allow for reuse
            title = $input.attr('title'),
            $form = $(this.form),
            $win = $(window);

            function remove() {
                if ($input.val() === title && $input.hasClass(blurClass)) {
                    $input.val('').removeClass(blurClass);
                }
            }

            // only apply logic if the element has the attribute
            if (title) {
                // on blur, set value to title attr if text is blank
                $input.blur(function() {
                    if (this.value === '') {
                        $input.val(title).addClass(blurClass);
                    }
                }).focus(remove).blur(); // now change all inputs to title

                // clear the pre-defined text when form is submitted
                $form.submit(remove);
                $win.unload(remove); // handles Firefox's autocomplete
            }
        });
    };

})(jQuery);

//jQuery plugin template 
(function($) {
    $.fn.myPlugin = function(options) {
        var defaults = { foo: 'bar', anothervalue: 5 };
        var defaults = $.extend(defaults, options);
        this.each(function() {
            // element-specific code here  
            defaults.foo; // this will get the option that was passed through the plugin, first it looks for default  
            // in this case foo is equal to the string bar  
        });
        return this;
    };
})(jQuery); 

$('input[title!=""]').jqpHint();

