/*=========================================\
Author      :  Jeff Antunes               \\
Version     :  1.0                        \\
Date Created:  May 11, 2010               \\
----------------------------              \\
Last Update:   12-MAY-2010                \\
----------------------------              \\
E-mail     :   jeffrey.antunes@disney.com \\
                                          \\
===========================================\
------------------------------------------*/

/******************************************/

/******************************************/

var contentSelectionEvents = new Array();
var button_event_bound = false; //need this to toggle if buttons have onclick events or not
var minisite = new Number();

function getContentTree(minisiteid, language){

    $.ajax({
            type: "GET",
            url: "/admin/dtai_ws.php?action=get_minisite_tree&minisiteid=" + minisiteid + "&langid=" + language + "&db=" + wsdbname,
            dataType: "xml",
            success: parseContentTree,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
    });
}

/******************************************/

/******************************************/

function postContentData(minisiteid, channelid, language, selected, cascade, terminate, siteid){

    

    $.ajax({
        type: "POST",
        url: "/admin/dtai_ws.php?action=edit_minisite_channel&minisiteid=" + minisiteid + "&channelid=" + channelid + "&langid=" + language + "&select=" + selected + "&cascade=" + cascade + "&terminate=" + terminate + "&siteid=" + siteid + "&db=" + wsdbname,
        dataType: "xml",
        async: false,
        success: function(data) {
        //alert('Load was performed.');
          },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
        }
    });
//        success: parseContentTree,
    
}

/******************************************/

/******************************************/

function includeToggle(){

    if($('#show').attr('checked') == true){
        if(($('#include').attr('src') == "/csb/_images/checkOn_Active.gif") || ($('#include').attr('src') == "/csb/_images/checkOn_Inactive.gif")) {
            $('#include').attr('src', "/csb/_images/checkOff_Active.gif");
        }else{
            $('#include').attr('src', "/csb/_images/checkOn_Active.gif");
        }
        return true;
    }else{
        $('#include').attr('src', "/csb/_images/checkOn_Inactive.gif");
        return false;
    }
    
}

function updateContent(minisiteid, language, status, siteid) {

    //console.log(updateContent.arguments);

    //alert(updateContent.arguments);

    //$("#loading").show();
    //$("#treebox").hide();

    var channelid = $("input[name=displayStatus]:checked").val();

    //$("#tree tbody").empty();

    //alert('checked: ' + $("#include").attr("checked") + "\ndisabled: " + $("#include").attr("disabled"));

    var include = 0;

    if(($('#include').attr('src') == "/csb/_images/checkOn_Active.gif") || (($('#include').attr('src') == "/csb/_images/checkOn_Inactive.gif" || $('#include').attr('src') == "/csb/_images/checkOff_Inactive.gif") && $('#show').attr('checked') == true) ) {
        //alert('include == 1');
            include = 1;
    }

    var cascade = 0;
    if(status == 1 && include == 1) {
        cascade = 1;
        $('#include').attr('src', "/csb/_images/checkOn_Active.gif");
    }

    //console.log("status: "+ status + "\ninclude: " + include + "\ncascade: " + cascade);


    var chan_tr = $("[name='" + channelid + "']");
    var start_node = parseInt(chan_tr.attr('id').split('-')[1]);
    //alert(start_node);

    this_span = $("[name='" + channelid + "'] td span:last");
    if(status == 0){
        this_span.addClass('hidden');
    }
    else{
        this_span.removeClass('hidden');
    }

    if((include == 1 || status == 0) || (include == 0 && status == 1) || (include == 1 && status == 1)){
        descendant = true;
        iter = 0;
        var prev_tr = chan_tr;
        var next_node = 0;
        while(descendant == true){
            iter++;
            next_lookup = "#node-" + (start_node + iter);
            next_tr = $(next_lookup);
            if(next_tr.length > 0){
            
                next_node = parseInt(next_tr.attr('id').split('-')[1]);
                child_of = parseInt(next_tr.attr('class').split('-')[3]);
                if(child_of >= start_node){
                    descendant = true;
                    this_channel = next_tr.attr('name');

                    //either of these conditions wipes all events previously applied below the node
                    //NOTE: canceling this behavior since it introduces complications on webservice side
//                     if(((include == 1) && (status == 1)) || status == 0){
//                         delete contentSelectionEvents[this_channel];
//                     }
                    
                    this_span = $(next_lookup + " td span:last");
                    if(status == 0){
                        this_span.addClass('hidden');
                    }
                    else if((include == 0) && (iter > 0)){
                        this_span.addClass('hidden');                        
                    }
                    else{
                        this_span.removeClass('hidden');
                    }
                }
                else{
                    //console.log({'breaking_loop':iter, 'node':next_node, 'child_of': child_of, 'status':status, 'include':include, 'cascade':cascade});
                    descendant = false;
                }
                prev_tr = next_tr;
            }
            else{
                //no next element, break out
                descendant = false;
            }
        }
    }

    contentSelectionEvents.push([channelid,language, status, cascade, include, siteid]);

    //console.log(contentSelectionEvents);

    //postContentData(minisiteid, channelid, language, status, cascade, include, siteid);

}

/******************************************/

/******************************************/

function saveContent(prev_cont){

//     alert(prev_cont);
    $("#treebox").hide();
    $("#loading").show();

    if(prev_cont == 'preview'){
        successFunc = function(){
            
            cspost = $('#content-selection').attr('action');
            //alert(cspost);
            $('#content-selection').attr('action', cspost + "?preview=1");
            $('#content-selection').submit();
        }
    }
    else{
        successFunc = function(){ $('#content-selection').submit(); }
    }

    //x = (x*-1) + 1;

    var language,status,cascade,include,siteid;

    //calling webservice multiple times as we loop
    for(e in contentSelectionEvents){

        channelid = contentSelectionEvents[e][0];
        language = contentSelectionEvents[e][1];
        status = contentSelectionEvents[e][2];
        cascade = contentSelectionEvents[e][3];
        include = ((contentSelectionEvents[e][4] * -1) + 1); //reversing boolean state of this
        siteid = contentSelectionEvents[e][5];
    
        postContentData(minisite, channelid, language, status, cascade, include, siteid);
    }

    $("#loading").hide();

    successFunc();

// TODO:
//     contentstring = new Array();
//     for(e in contentSelectionEvents)
//     {
//         contentstring.push([e].concat(contentSelectionEvents[e]));
//     }
// 
//     //console.log(contentstring);
//     
//     //decodeURIComponent($.param(contentSelectionEvents));
// 
//     $.ajax({
//         type: "POST",
//         url: "/admin/dtai_ws.php?action=edit_minisite_channel&db=" + wsdbname + "&update=" + encodeURIComponent('[[' + contentstring.join('],[') + ']]'),
//         dataType: "xml",
//         success: successFunc,
//         error: function(XMLHttpRequest, textStatus, errorThrown) {
//                 alert("ERROR: " + textStatus);
//         }
//     });

}


/******************************************/

/******************************************/

function parseContentTree(xml){

    $(xml).find("minisite").each(function() {

        //making minisite a global
        minisite = $(this).attr("minisiteid");
        var segmentlist = $(this).attr("segmentlist");
        var language = $(this).attr("langid");

        $(this).find("*").each(function() {

            var channelid = $(this).attr("contentid");

            if( $(this).attr("NodeID") == 1 ){
                $("#tree tbody").append('<tr name=\"' + channelid + '\" id=\"node-' + $(this).attr("NodeID") + '\"><td><span class="' + $(this).attr("contenttype") + '">' + $(this).attr("name") + '</span></td></tr>');
            } else {

                if( $(this).attr("isinminisite") == 1 ){
                    $("#tree tbody").append('<tr name=\"' + channelid + '\" id=\"node-' + $(this).attr("NodeID") + '\" class=\"child-of-node-' + $(this).attr("ParentNodeID") + '\"><td onclick="getContentDetails(' + minisite + ', \'' + channelid + '\', \'' + segmentlist + '\', \'' + language + '\')"><span class="' + $(this).attr("contenttype") + '">' + $(this).attr("name") + '</span></td></tr>');
                } else {
                    $("#tree tbody").append('<tr name=\"' + channelid + '\" id=\"node-' + $(this).attr("NodeID") + '\" class=\"child-of-node-' + $(this).attr("ParentNodeID") + '\"><td onclick="getContentDetails(' + minisite + ', \'' + channelid + '\', \'' + segmentlist + '\', \'' + language + '\')"><span class="' + $(this).attr("contenttype") + ' hidden">' + $(this).attr("name") + '</span></td></tr>');
                }

            }

        })
        updateContentTree();
        $('#tree tbody tr:first td span').trigger('click');
    });
}

/******************************************/

/******************************************/

function updateContentTree() {

    $("#tree").treeTable({
      expandable: true,
      initialState: "collapsed"
    });

    // Configure draggable nodes
//     $("#tree .CHANNEL, #tree .GROUP").draggable({
//       helper: "clone",
//       opacity: .75,
//       refreshPositions: true, // Performance?
//       revert: "invalid",
//       revertDuration: 300,
//       scroll: true
//     });

    // Configure droppable rows
//     $("#tree .GROUP").each(function() {
//       $(this).parents("tr").droppable({
//         accept: ".CHANNEL, .GROUP",
//         drop: function(e, ui) {
//           // Call jQuery treeTable plugin to move the branch
//           $($(ui.draggable).parents("tr")).appendBranchTo(this);
//         },
//         hoverClass: "accept",
//         over: function(e, ui) {
//           // Make the droppable branch expand when a draggable node is moved over it.
//           if(this.id != $(ui.draggable.parents("tr")[0]).id && !$(this).is(".expanded")) {
//             $(this).expand();
//           }
//         }
//       });
//     });

    // Make visible that a row is clicked
    $("#tree tbody tr").mousedown(function() {
      $("tr.selected").removeClass("selected"); // Deselect currently selected rows
      $(this).addClass("selected");
    });

    // Make sure row is selected when span is clicked
    $("#tree tbody tr span").mousedown(function() {
      $($(this).parents("tr")[0]).trigger("mousedown");
    });

    $("#loading").hide();
    $("#treebox").show();
}

/******************************************/

/******************************************/

function getContentDetails(minisiteid, channelid, segmentlist, language){

    $("#selectYourContent").hide();
    $("#contentInfo").hide();
    $("#loading57").show();

    $.ajax({
        type: "POST",
        url: "/admin/dtai_ws.php?action=get_content_details&minisiteid=" + minisiteid + "&channelid=" + channelid + "&langid=" + language + "&segmentlist=" + segmentlist + "&db=" + wsdbname,
        dataType: "xml",
        success: viewContentDetails,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
        }
    });
}

/******************************************/

/******************************************/

function viewContentDetails(xml){

    //add content update behavior to main submit buttons
    if(!button_event_bound){ 
        $('#preview').click(function(event){
            event.preventDefault();
            saveContent('preview');
        });
        $('#preview').next('input').click(function(event){
            event.preventDefault();
            saveContent();
        });
        button_event_bound = true;
    }
    
    $(".contentName").empty();
    $("#parentDestination").empty();
    $("#asset").empty();
    $("ul#contentLanguages").empty();
    $("#sampleContent").empty();

    $(xml).find("content").each(function() {

        var channelid = $(this).attr("contentid");
        var name = $(this).attr("name");
        var destination = $(this).attr("parent_destination");
        var assetname = $(this).attr("assetname");
        var assetpath = $(this).attr("assetpath");
        var isinminisite = $(this).attr("isinminisite");
        var isselected = $(this).attr("isselected");
        //var cascade = $(this).attr("cascade");
        var hidden = $(this).attr("hidden");
        var terminate = $(this).attr("terminate");

        $(".contentName").append(name);
        $("#parentDestination").append(destination);

        // IMAGE NOT AVAILABLE
        if(assetpath == ""){
            $("#asset").append("<img src='/csb/_images/icons/not-available.gif' height='100' />");
        } else {
            $("#asset").append("<img src='http://www.disneytravelagents.com/" + assetpath + "' height='100' alt='" + assetname + "' />");
        }

        $(this).find("language").each(function() {

            var langid = $(this).attr("langid");
            var langtext = $(this).attr("langtext");
            var pages = $(this).attr("numchannels");
			pages++;
			
            //$("ul#contentLanguages").append("<li>LANGUAGE</li>");
            $("#contentLanguages").append("<li style='list-style:none; padding:2px; white-space:nowrap'><img src='/csb/_images/icons/country-flags/" + langid + ".png' align='absmiddle' /> " + langtext + " (" + pages + " pages)</li>");

        });

        $('#show').attr('value', channelid);
        $('#hide').attr('value', channelid);



        //changing behavior here to reflect client-side changes to content tree

        //alert(channelid);
        
        var chan_tr = $("[name='" + channelid + "']");
        var nodenum = parseInt(chan_tr.attr('id').split('-')[1]);
        
        //default conditions
        var hidden = false;
        var include = true;


        //alert($("#node-" + nodenum + " td span:last").hasClass('hidden'));
        //visible but with ANY hidden child means NO include
        if(!($("#node-" + nodenum + " td span:last").hasClass('hidden'))){
            hidden = false

//            if((include == 1 || status == 0) || (include == 0 && status == 1) || (include == 1 && status == 1)){
            descendant = true;
            iter = 0;
            var prev_tr = chan_tr;
            var next_node = 0;
            while(descendant == true){
                iter++;

                next_lookup = "#node-" + (nodenum + iter);
                next_tr = $(next_lookup);
                if(next_tr.length > 0){

                    next_node = parseInt(next_tr.attr('id').split('-')[1]);
                    child_of = parseInt(next_tr.attr('class').split('-')[3]);
                    if(child_of >= nodenum){
                        descendant = true;
                        this_channel = next_tr.attr('name');
                        this_span = $(next_lookup + " td span:last");
                        if(this_span.hasClass('hidden')){
                            include = false;
                        }
                    }
                    else{
                        //console.log({'breaking_loop':iter, 'node':next_node, 'child_of': child_of, 'status':status, 'include':include, 'cascade':cascade});
                        descendant = false;
                    }
                    prev_tr = next_tr;
                }
                else{
                    //no next element, break out
                    descendant = false;
                }
            }
//            }



            //alert('hidden: ' + hidden + "\ninclude: " + include);

  
        }
        else{
            hidden = true;
        }       

//         alert('hidden: ' + hidden + "\ninclude: " + include);

        if(hidden == false){


            $('#show').attr('checked', true);

            if(include == true){
                $('#include').attr('checked', true)
                $('#include').attr('src', "/csb/_images/checkOn_Active.gif");
            }
            else
            {
                $('#include').attr('checked', false);
                $('#include').attr('src', "/csb/_images/checkOff_Active.gif");
            }


        } else {
            $('#hide').attr('checked', true);
            //$('#include').attr('disabled', true);
            $('#include').attr('src', "/csb/_images/checkOff_Inactive.gif");
        }


// // --old behavior:

//         if(isinminisite == 1){
// 
// 
//             $('#show').attr('checked', true);
//             $('#include').attr('disabled', false);
// 
//             if(terminate == 0){
//                 $('#include').attr('checked', true);
//             } else {
//                 $('#include').attr('checked', false);
//             }
// 
//         } else {
//             $('#hide').attr('checked', true);
//             $('#include').attr('disabled', true);
//         }






        $(this).find("sample_content").each(function() {

            var sample = $(this).attr("html");

            $("#sampleContent").append(sample);

        });

        $("#contentInfo").show();
        $("#loading57").hide();

    });

}

/******************************************/

/******************************************/

function searchUserEntity( search_word, groupid_bu, moduleid, siteid, page ) {

    var limit = 5;
    var offset = page * limit;
    
    var searchFilter = "all";
    if($('input:radio[name=searchFilter]')) {
    	searchFilter = $('input:radio[name=searchFilter]:checked').val();
    } else if($('input:hidden[name=searchFilter]')) {
    	searchFilter = $('input:hidden[name=searchFilter]').val();
    }
    var dataString = "searchfilter=" + searchFilter + "&search=" + search_word + "&groupid_bu=" + groupid_bu + "&limit=" + limit + "&offset=" + offset + "&db=" + wsdbname;

    var loading = "#loading" + moduleid + "";

    if(search_word==''){
    } else {
        $.ajax({
            type: "GET",
            url: "/admin/dtai_ws.php?action=search_admin_user_entity",
            data: dataString,
            cache: false,
            beforeSend: function(html){
                document.getElementById("insert_search").innerHTML = '';
                    $("#searchword").hide();
                    $("#pages").hide();
                    $("#pages").empty();
                    $(loading).show();
                },
            success: function(xml){
                $("#searchword").show();
                $("#insert_search").show();
                //$("#insert_search").append(html);

                $(xml).find("data").each(function() {

                    $(this).find("searchinfo").each(function() {
                        $("#searchword").html( '<strong>' + $(this).attr("count") + '</strong> results for "' + search_word + '"' );

                        // ADDITIONAL RESULT PAGES
                        if(page > 0) {
                            $("#pages").append('<a style="color:blue;" href="javascript:searchUserEntity(\'' + search_word + '\', ' + groupid_bu + ',' +
                                    moduleid + ',' + siteid + ',' + (page-1) + ');">&laquo; Previous results</a>' );
                        }
                        if( $(this).attr("count") > (offset + limit) ) {
                            if(page > 0) {
                                $("#pages").append(' | ');
                            }
                            $("#pages").append('<a style="color:blue;" href="javascript:searchUserEntity(\'' + search_word + '\', ' + groupid_bu + ',' +
                                    moduleid + ',' + siteid + ',' + (page+1) + ');">More results &raquo;</a>' );
                        }

                        $("#pages").show();
                    })

                    $(this).find("results").each(function() {

                        if( $(this).attr("type") == 'USER' || $(this).attr("type") == 'ENTITY_USER') {      // USER RESULT

                            $("ul#insert_search").append('<li><div style="display:table; float:left; padding-right:5px">' +
                            		'<a href="javascript:getUserProfile(' + $(this).attr("userid") + ', ' + groupid_bu + ', ' + moduleid + ')">' +
                            		'<img src="/csb/_images/icons/types/' + $(this).attr("type") + '.gif" />' +
                                    '</a></div><div style="display:table"><a href="javascript:getUserProfile(' + $(this).attr("userid") + ', ' + 
                                    groupid_bu + ', ' + moduleid + ')"><strong>' +
                                $(this).attr("name") +
                            '</strong></a><br />' +
                                $(this).attr("email") +
                            '<br /><strong><em>' +
                                $(this).attr("username") +
                            '</em></strong></div></li>'
                            );

                        } else {    // ENTITY RESULT

                            $("ul#insert_search").append('<li><div style="display:table; float:left; padding-right:5px">' +
                            		'<a href="javascript:getEntityProfile(' + $(this).attr("entityseqid") + ', ' + groupid_bu + ', ' + 
                            		moduleid + ',' + siteid + ',0)"><img src="/csb/_images/icons/types/' + $(this).attr("type") +
                                    '.gif" /></a></div><div style="display:table"><a href="javascript:getEntityProfile(' + 
                                    $(this).attr("entityseqid") + ', ' + groupid_bu + ', ' + moduleid + ',' + siteid + ',0)"><strong>' +
                                $(this).attr("name") +
                            '</strong></a><br /><strong>' +
                                $(this).attr("referencetype") +
                            ':</strong> ' +
                                $(this).attr("referenceid") +
                            '</div></li>'
                            );

                        }

                    })

                });

                $(loading).hide();
            }

        });
    }
}


function searchEntityUsers( search_word, groupid_bu, moduleid, siteid, entityid, page ) {

    var limit = 10;
    var offset = page * limit;

    var dataString = "search=" + search_word + "&groupid_bu=" + groupid_bu + "&entityseqid=" + entityid + "&limit=" + limit + "&offset=" + offset + "&db=" + wsdbname;

    var loading = "#loading" + moduleid + "";


    if(search_word==''){
    } else {
        $.ajax({
            type: "GET",
            url: "/admin/dtai_ws.php?action=search_admin_user_entity",
            data: dataString,
            cache: false,
            beforeSend: function(html){
                document.getElementById("insert_search").innerHTML = '';
                    $("#searchword").hide();
                    $("#pages").hide();
                    $("#pages").empty();
                    $(loading).show();
                },
            success: function(xml){
                $("#searchword").show();
                $("#insert_search").show();

                $(xml).find("data").each(function() {

                    $(this).find("searchinfo").each(function() {
                        $("#searchword").html( '<strong>' + $(this).attr("count") + '</strong> results for "' + search_word + '"' );

                        // ADDITIONAL RESULT PAGES
                        if(page > 0) {
                            $("#pages").append('<a style="color:blue;" href="javascript:searchUserEntity(\'' + search_word + '\', ' + groupid_bu + ',' +
                                    moduleid + ',' + (page-1) + ');">&laquo; Previous results</a>' );
                        }
                        if( $(this).attr("count") > (offset + limit) ) {
                            if(page > 0) {
                                $("#pages").append(' | ');
                            }
                            $("#pages").append('<a style="color:blue;" href="javascript:searchUserEntity(\'' + search_word + '\', ' + groupid_bu + ',' +
                                    moduleid + ',' + (page+1) + ');">More results &raquo;</a>' );
                        }

                        $("#pages").show();
                    })

                    $(this).find("results").each(function() {
                        if( $(this).attr("type") == 'USER' || $(this).attr("type") == "ENTITY_USER") {
                            $("ul#insert_search").append('<li><div style="display:table; float:left; padding-right:5px">' +
                            		'<a href="javascript:getUserProfile(' + $(this).attr("userid") + ', ' + groupid_bu + ', ' + moduleid + ')">' +
                            		'<img src="/csb/_images/icons/types/' + $(this).attr("type") + '.gif" />' +
                                    '</a></div><div style="display:table"><a href="javascript:getUserProfile(' + $(this).attr("userid") + ', ' + groupid_bu + ', ' + moduleid + ')"><strong>' +
                                $(this).attr("name") +
                            '</strong></a><br />' +
                                $(this).attr("email") +
                            '<br /><strong><em>' +
                                $(this).attr("username") +
                            '</em></strong></div></li>'
                            );
                        }

                    })

                });

                $(loading).hide();
            }

        });
    }
}

/******************************************/

/******************************************/

function getUserProfile(userid, groupid_bu, moduleid){

    hideUserEntity(moduleid);
    if(moduleid == 72) {
        $("#searchentityuser").hide();
    }
    if(moduleid == 62) {
        $("#loading64").show();
    }

    //alert("UserID: " + userid );
    //alert("GroupID: " + groupid_bu );
    //alert("DB Name: " + wsdbname );
    
    // GET USER PROFILE DATA
    $.ajax({
            type: "POST",
            url: "/admin/dtai_ws.php?action=get_user_profile&userid=" + userid + "&groupid_bu=" + groupid_bu + "&db=" + wsdbname,
            dataType: "xml",
            success: function(xml) {
		        $(xml).find("user").each(function() {
		            $("#userid").val($(this).attr("userid"));
		            $("#currentuseraccess").val($(this).attr("access_level"));
		            $("#useraccess").val($(this).attr("access_level"));
		            $("#userInfo").append (
		                '<div style="float:right">Last logged in on ' +
		                    $(this).attr("lastlogin") +
		                '</div><div class="bigHeader"><strong>' + $(this).attr("name") + '</strong></div>' +
		                    $(this).attr("email") +
		                '<div class="header"><em>' +
		                    $(this).attr("username") +
		                '</em></div>'
		            );
		            
		        });
		
		        $(xml).find("entity").each(function() {
		            $("#entityInfo").append(
		                    $(this).attr("entity_name") +
		                '<br />' +
		                    $(this).attr("addr1") +
		                '<br />' +
		                    $(this).attr("city") +
		                ', ' +
		                    $(this).attr("state") +
		                '&nbsp;&nbsp;' +
		                    $(this).attr("zip") +
		                '<br />' +
		                    $(this).attr("country")
		            );
		        });
		        
		        var hasMinisites = false;
		        $(xml).find("minisites").each(function() {
		        	showMinisiteControls($(this).attr("count"), 1);
		        });
		        
		    	$("#sitesbody").empty();
		    	$(xml).find("minisite").each(function() {
		    		hasMinisites = true;
		    		showMinisite($(this).attr("minisiteid"), $(this).attr("name"), $(this).attr("alias"), 
		    				$(this).attr("format"), $(this).attr("langid"), $(this).attr("createddate"), 
		    				$(this).attr("updateddate"), $(this).attr("status"), $(this).attr("isassigned"),
		    				$(this).attr("isauthorized"));
		    	});
		
		        $("#userProfile").show();
		        if(moduleid == 62) {
		            $("#loading64").hide();
		        }
    		},
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
    });

}

function getUserProfileMinisites(userid, groupid_bu, moduleid, page){

	var offset = (page-1) * 25;
	
    // GET USER PROFILE DATA
    $.ajax({
            type: "GET",
            url: "/admin/dtai_ws.php?action=get_user_profile&userid=" + userid + "&groupid_bu=" + groupid_bu + "&offset=" + offset + "&db=" + wsdbname,
            dataType: "xml",
            success: function(xml) {
		        $(xml).find("entity").each(function() {
		            
		            var hasMinisites = false;
		            $(this).find("minisites").each(function() {
		            	showMinisiteControls($(this).attr("count"), page);
		
		                $("#sitesbody").empty();
		                $(this).find("minisite").each(function() {
		                	hasMinisites = true;
		        			showMinisite($(this).attr("minisiteid"), $(this).attr("name"), $(this).attr("alias"), 
		        					$(this).attr("format"), $(this).attr("langid"), $(this).attr("createddate"), 
		        					$(this).attr("updateddate"), $(this).attr("status"), $(this).attr("isassigned"),
		        					$(this).attr("isauthorized"));
		                });	
		            });
		        });
    		},
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
    });

}

/******************************************/

/******************************************/

function getEntityProfile( entityid, groupid_bu, moduleid, siteid, page ) {

    hideUserEntity(moduleid);
    if(moduleid == 62) {
        $("#loading64").show();
    }
    
    // user limit and offset
    limit = 10;
    offset = page * limit;

    // GET ENTITY PROFILE DATA
    $.ajax({
            type: "GET",
            url: "/admin/dtai_ws.php?action=get_entity_profile&entityid=" + entityid + "&groupid_bu=" + groupid_bu + "&siteid=" + siteid + "&limit=" + limit + "&offset=" + offset + "&db=" + wsdbname,
            dataType: "xml",
            success: parseEntityProfileXml,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
    });

    function parseEntityProfileXml(xml){

        $(xml).find("entity").each(function() {

            $("#entityseqid").val($(this).attr("entityseqid"));

            $("#entityProfileInfo").append('<div class="header">' + $(this).attr("entity_name") + '</div>');
            if($(this).attr("addr1") != "") {
                $("#entityProfileInfo").append('<div>' + $(this).attr("addr1") + '<br/>');
            }
            if($(this).attr("addr2") != "") {
                $("#entityProfileInfo").append('<div>' + $(this).attr("addr2") + '<br/>');
            }
            if($(this).attr("addr3") != "") {
                $("#entityProfileInfo").append('<div>' + $(this).attr("addr3") + '<br/>');
            }
            $("#entityProfileInfo").append('<div>' + $(this).attr("city") + ', ' +
                $(this).attr("state") + ' ' + $(this).attr("zip") +
                '<br/>' + $(this).attr("country") + '</div>');

            var entityReference = "";
            $(this).find("entityreference").each(function() {
            	if($(this).attr("isdefault") == "1" || entityReference == "") {
            		entityReference = $(this).attr("referenceid");
            	}
            });
            
            var userCount = $(this).find("users").attr("count");
            if(userCount < 100 || moduleid != 72) {

                $(this).find("user").each(function() {
                    $("ul#entityProfileUsers").append(
                        '<li><div style="display:table; float:left; padding-right:5px">' +
                		'<a href="javascript:getUserProfile(' + $(this).attr("userid") + ', ' + groupid_bu + ', ' + moduleid + ')">' +
                		'<img src="/csb/_images/icons/types/USER.gif" /></a></div>' +
                        '<div style="display:table"><a href="javascript:getUserProfile(' +
                        $(this).attr("userid") + ', ' + groupid_bu + ', ' + moduleid + ')"><strong>' +
                        $(this).attr("name") + '</strong></a><br />' + $(this).attr("email") +
                        '<br /><strong><em>' + $(this).attr("username") + '</em></strong></div></li>');
                });

                $("#entityProfileUserTopControls").append('<strong>Total users</strong>: ' + userCount + ' (Showing users ' +
                    (offset+1) + ' - ' + ((offset+limit) > userCount ? userCount : (offset+limit)) + ')<br/>' +
                    '<a style="color:blue;" href="/csb/home/invitations/?entityref=' + entityReference + '">Invite A New User</a><br/>');

                if(page > 0) {
                    $("#entityProfileUserBottomControls").append(
                        '<a style="color:blue;" href="javascript:getEntityProfile(' + entityid + ',' + groupid_bu + ',' + moduleid + ',' + siteid + ',' + (page-1) + ');">&laquo; Previous users</a>');
                }

                if((offset + limit) < userCount) {
                    if(page > 0) {
                        $("#entityProfileUserBottomControls").append(' | ');
                    }
                    $("#entityProfileUserBottomControls").append(
                        '<a style="color:blue;" href="javascript:getEntityProfile(' + entityid + ',' + groupid_bu + ',' + moduleid + ',' + siteid + ',' + (page+1) + ');">More users &raquo;</a>');
                }
            } else {
                $("#entityProfileUserTopControls").append('<strong>Total users</strong>: ' + userCount + '<br/>' +
                        '<a style="color:blue;" href="/csb/home/invitations/?entityref=' + entityReference + '">Invite A New User</a><br/>');
                $("#entityProfileUserSearch").show();
            }

            $("#defaultrole").empty();
            $(this).find("rolegroup").each(function() {
                if($(this).attr("select") == "1") {
                    $("#defaultrole").append("<option value=\"" + $(this).attr("groupid") + "\" selected=\"selected\">" + $(this).attr("name") + "</option>");
                } else {
                    $("#defaultrole").append("<option value=\"" + $(this).attr("groupid") + "\">" + $(this).attr("name") + "</option>");
                }
            });

        });
        
        if(moduleid != 72) {
	        $(xml).find("minisites").each(function() {
	        	showEntityMinisiteControls($(this).attr("count"), 1);
	        });
	        
	    	$("#entitysitesbody").empty();
	    	$(xml).find("minisite").each(function() {
	    		showEntityMinisite($(this).attr("minisiteid"), $(this).attr("name"), $(this).attr("alias"), 
	    				$(this).attr("format"), $(this).attr("langid"), $(this).attr("createddate"), 
	    				$(this).attr("updateddate"), $(this).attr("status"));
	    	});
        }

        $("#entityProfile").show();
        if(moduleid == 62) {
            $("#loading64").hide();
        }
    }
}

function getEntityProfileMinisites( entityid, groupid_bu, moduleid, siteid, page ) {

	// minisite limit and offset
    limit = 25;
    offset = (page-1) * limit;

    // GET ENTITY PROFILE DATA
    $.ajax({
            type: "GET",
            url: "/admin/dtai_ws.php?action=get_entity_profile&entityid=" + entityid + "&groupid_bu=" + groupid_bu + "&siteid=" + siteid + "&sitelimit=" + limit + "&siteoffset=" + offset + "&db=" + wsdbname,
            dataType: "xml",
            success: function(xml) {
		        $(xml).find("minisites").each(function() {
		        	showEntityMinisiteControls($(this).attr("count"), page);
		        });
		        
		    	$("#entitysitesbody").empty();
		    	$(xml).find("minisite").each(function() {
		    		showEntityMinisite($(this).attr("minisiteid"), $(this).attr("name"), $(this).attr("alias"), 
		    				$(this).attr("format"), $(this).attr("langid"), $(this).attr("createddate"), 
		    				$(this).attr("updateddate"), $(this).attr("status"));
		    	});
    		},
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
    });

}

function editEntitySiteGroup(entityid, groupid, siteid) {
    $.ajax({
        type: "POST",
        url: "/admin/dtai_ws.php?action=edit_siteentitygroup&entityseqid=" + entityid + "&groupid=" + groupid + "&siteid=" + siteid + "&db=" + wsdbname,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}

/* USE ME OR DELETE ME
function getPages(count, limit) {

    var remainder = count % limit;
    var quotient = (count - remainder) / limit;
    if(remainder == 0) {
        return quotient;
    } else {
        return quotient + 1;
    }
}*/

function hideUserEntity(moduleid) {

    $("#searchinfo").hide();
    $("#userProfile").hide();

    $("#userInfo").empty();
    $("#entityInfo").empty();
    $("#availableSites").empty();
    $("#assignedSites").empty();

    if(moduleid != 72) {
        $("#entityProfile").hide();
        $("#entityProfileInfo").empty();
        $("ul#entityProfileUsers").empty();
        $("#entityProfileUserTopControls").empty();
        $("#entityProfileUserBottomControls").empty();
    }

}

/*----------------------------------------*/
