﻿var TCSel;
var TCPrevious;

function GoBack(value) {
    if (value == "List") {
        //$("#GoBack").hide();
        $("#List").show();
        $("#Details").hide();
    }
    //alert(value);
}

//$.history.callback = function(reinstate, cursor) {
//    // check to see if were back to the beginning without any stored data
//    alert("Callback");
//    /*    if (typeof (reinstate) == 'undefined')
//    counter = 0;
//    else
//    counter = parseInt(reinstate.counter) || 0;
//    $('#counter').html('{\'counter\':' + counter.toString() + '}');*/
//};

function GetCombo(value) {

    //$.history({'ComboValue':value});
    //value = inObj.value;
    if (value != null && value != "")
        $("#cboSearchBy")[0].value = value;
    else if (value == "") {
        value = "AllProjects";
        $("#cboSearchBy")[0].value = value;
    }

    var id = $("#cboSearchBy")[0].value;

    if (TCSel == id)
        return;

    TCPrevious = TCSel;
    TCSel = id;

    //$("#GoBack").hide();
    $("#List").hide();
    $("#Details").hide();
    $("#searchbtn").hide();
    $("#TCBreadCrumb").hide();    
    $("#SelectCombo").next().remove();
    $("#SelectCombo").unbind();
    
    var divSearch = $("#SearchBy2")[0];
    divSearch.innerHTML = "";
    $("#Err").innerHTML = "";
    $("#Err").className = "";   

    if (id == "GeoCoverage") {
        Color = "#034EA2";
        TCTitle = "Geographical Coverage";
        //$("#" + id).css("background-image", "url(/Web/TC/Images/THEMATIC-CLUSTER-sans-texte.gif)");
    }
    else if (id == "Donor") {
        Color = "#FCAF17";
        TCTitle = "Donor";
    }
    else if (id == "ThematicCluster") {
        Color = "#00A650";
        TCTitle = "Thematic Cluster";
    }
    else if (id == "AllProjects") {
        Color = "#EC1C24";
        TCTitle = "All Projects";
    }
    else if (id == "SeeProject") {
        Color = "#0095D9";
        TCTitle = "Project ID";
    }

    if (TCPrevious != undefined) {
        $("#" + TCPrevious).css("background", "transparent url(/Web/TC/Images/" + TCPrevious + ".gif) no-repeat");
        $("#" + TCPrevious).toggleClass("imgMenuout");
    }
    //$("#" + TCPrevious).toggleClass("#" + TCPrevious);
    $("#" + id).css("background", "url(/Web/TC/Images/" + TCSel + "E.gif) no-repeat");
    $("#" + id).removeClass("imgMenuout");

    $("#reContainer").css({ 'background-color': Color, 'font-weight': 'bolder' });
    $("#title").html("Technical Cooperation Projects<BR/>" + TCTitle).show("fast");
    
    if (id == "SeeProject") {
        var id = $("#SearchBy2")[0];
        //id.innerHTML = "<DIV id='search-box'><DIV class='search-wrapper'><INPUT class='textfield' id='byProject' onblur=\"if(this.value=='') this.value='Search...';\" onfocus=\"if(this.value=='Search...') this.value='';\" name='s' value='Search...' /></DIV><div id='display'></div></DIV></DIV>";
        //id.innerHTML = "<DIV id='search-box'><DIV class='search-wrapper'><INPUT class='textfield' id='byProject'/></DIV><div id='display'></div></DIV></DIV>";
        id.innerHTML = "<DIV id='search-box' style='position:absolute'><DIV class='search-wrapper'><INPUT class='textfield' id='byProject' onkeyup ='this.value=this.value.toUpperCase()'/></DIV></DIV></DIV>";

     
        //$("#byProject").autocomplete("/Web/TC/Autocomplete.ashx", { onItemSelect: OpenProject($("#byProject")[0].value)});
     

        /*Move the SearchBy2*/
        //var pos = $("#" + value).offset();
        var pos = $("#posCombo").offset();
        var height = 0;
        //var height = $("#" + value).height();
        //$("#SearchBy2").css({ "left": (pos.left) + "px", "top": (pos.top + height +20) + "px" }).show();
        $("#SearchBy2").css({ "left": 10 + "px", "top": 10 + "px" }).show();
        $("#byProject").focus();

        //$("#search-box").show();
        $("#searchbtn").show();
        /*$("#byProject").keyup(function() {
            KeyUp();
        });*/
      /*  $("#byProject").autocomplete("/Web/TC/TCWebService.asmx/AutoComplete",
		{
		    delay: 10,
		    minChars: 1,
		    matchSubset: 1,
		    matchContains: 1,
		    cacheLength: 10,
		    onItemSelect: selectItem,
		    onFindValue: findValue,
		    formatItem: formatItem,
		    autoFill: true
		}*/
		
		/*$("#byProject").autocompleteArray(
		[
			"Aberdeen", "Ada", "Adamsville", "Addyston", "Adelphi", "Adena", "Adrian", "Akron",
						"New Concord", "New Hampshire", "New Haven", "New Holland",			
			"Zoar"
		],
		{
			delay:10,
			minChars:1,
			matchSubset:1,
			onItemSelect:selectItem,
			onFindValue:findValue,
			autoFill:true,
			maxItemsToShow:10
		});*/
/*        $("#byProject").autocomplete("/Web/TC/TCWebService.asmx/AutoComplete"
            parse: function(data) {
            var parsed = [];

            $(data).find("string").each(function() {
                parsed[parsed.length] = {
                    data: [$(this).text()],
                    value: $(this).text(),
                    result: [$(this).text()]
                };
            });
            return parsed;
        },
		{
		    delay: 10,
		    minChars: 1,
		    matchSubset: 1,
		    matchContains: 1,
		    cacheLength: 10,
		    onItemSelect: selectItem,
		    onFindValue: findValue,
		    formatItem: formatItem,
		    autoFill: true
		}
		*/
    }
    else if (id == "AllProjects") {
      
        //UnctadTC.TCWebService.Search(id, "", "", SucceededSearchBy, onDataFailure);
        CallSearch(id, "", ""); 
    }    
    else if (id != "" && id != "EmptyOption") {
        /*divSearch.style.backgroundImage = 'url(/web/tc/images/ajax-loader.gif)';
        divSearch.style.backgroundRepeat = 'no-repeat';
        divSearch.style.backgroundPosition = 'center';*/
    /*$("#progressBackgroundFilter").show();
    $("#progressBackgroundFilter").show();*/
        
        /*$get("progressBackgroundFilter").style.visibility = 'visible';
        $get("processMessage").style.visibility = 'visible';*/
    //UnctadTC.TCWebService.getCombo(id, "", SucceededCallbackCombo, onDataFailure);
    
    /*$("#imgMenu ul li a").animate({ width: "128px" }, { queue: false, duration: 450 });
    if (value != null)
    $("#" + value).animate({ width: "300px" }, { queue: false, duration: 450 });*/


    //var pos = $("#" + value).offset();
    //var width = $("#" + value).width();
    //var height = $("#" + value).height();
    var pos = $("#posCombo").offset();    
    var height = 0;   

    $("#SearchBy2").css({ "left": (pos.left) + "px", "top": (pos.top + height) + "px" }).show();
    var itemID = { "Value": id, "Type": ""};
    var jsonStr = JSON.stringify(itemID);
    
    $("#progressBackgroundFilter")[0].style.visibility = 'visible';
    $("#processMessage")[0].style.visibility = 'visible';
    
    $.ajax({
        type: "POST",
        url: "/Web/TC/TCWebService.asmx/getCombo",
        data: jsonStr,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: SucceededCallbackCombo,
        error: function(xhr, result) {
            AjaxFailed(xhr, result);
        }
    });
    }
  /*  else
        divSearch.style.backgroundImage = 'none';*/
}
/*
function findValue(li) {
    if (li == null) return alert("No match!");

    // if coming from an AJAX call, let's use the CityId as the value
    if (!!li.extra) var sValue = li.extra[0];

    // otherwise, let's just display the value in the text box
    else var sValue = li.selectValue;

    alert("The value you selected was: " + sValue);
}

function selectItem(li) {
    findValue(li);
}

function formatItem(row) {
    return row[0] + " (id: " + row[1] + ")";
}


function KeyUp() {
    var searchbox = $("#byProject").val();
    if (searchbox.length < 2)
    { }
    else {
        var itemID = { "Prefix": searchbox };
        var jsonStr = JSON.stringify(itemID);    

        $.ajax({
            type: "POST",
            url: "/Web/TC/TCWebService.asmx/AutoComplete",
            data: jsonStr,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: KeyUpOk,
            error: function(xhr, result) {
                AjaxFailed(xhr, result);
            }
        });
    } return false;

}

function KeyUpOk(Result) {
    $("#display").html(Result.d).show();
}
*/

function CallSearch(FieldName, FieldValue, SortOrder) {
    if ((FieldName != "" && FieldValue != "") || FieldName == "AllProjects") {
        $("#progressBackgroundFilter")[0].style.visibility = 'visible';
        $("#processMessage")[0].style.visibility = 'visible';
        var itemID = { "FieldName": FieldName, "FieldValue": FieldValue, "SortOrder": SortOrder };
        var jsonStr = JSON.stringify(itemID);
        $.ajax({
            type: "POST",
            url: "/Web/TC/TCWebService.asmx/Search",
            data: jsonStr,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: SucceededSearchBy,
            error: function(xhr, result) {
                AjaxFailed(xhr, result);
            }
        });
    }
    else {
        $("#List").hide();
        $("#Details").hide();
    }    
}
function AjaxFailed(xhr, result) {
    $("#progressBackgroundFilter")[0].style.visibility = 'hidden';
    $("#processMessage")[0].style.visibility = 'hidden';
    //var errorMessage = error.get_message();
    //alert(xhr.responseText);
    if (typeof result != "string")
        $("#Err")[0].innerHTML = result.status + ' ' + result.statusText;
    else
        $("#Err")[0].innerHTML = xhr.responseText;
    
    $("#Err")[0].className = "error";
}

function SucceededCallbackCombo(ajaxResponse) {
    $("#SearchBy2").html(ajaxResponse.d).show();    
    $("#SelectCombo").sSelect({ddMaxHeight: '300px'}); 
    $("#progressBackgroundFilter")[0].style.visibility = 'hidden';
    $("#processMessage")[0].style.visibility = 'hidden';
}

function SearchBy(sortOrder) {
    var id = $("#cboSearchBy")[0].value;
    if (id == "")
        return;

    $("#Err")[0].innerHTML = "";
    $("#Err")[0].className = "";       
    /*$("#progressBackgroundFilter")[0].style.visibility = 'visible';
    $("#processMessage")[0].style.visibility = 'visible';*/

    if (sortOrder == "")
        $("#processText")[0].innerHTML = "Loading ...<br>";
    else
        $("#processText")[0].innerHTML = "Sorting by " + sortOrder + "<br>";
    if (id == "SeeProject") {
        //var Ctrl = $("#byProject").val;
        //var id = $("#byProject").val;
        OpenProject($("#byProject")[0].value);       
    }
    else {
        var combo = $("#SelectCombo")[0];
        if (combo != null && id != "AllProjects")
            var Value = combo.value;
        else {
            var Value = "";
        }
            CallSearch(id, Value, sortOrder);
    }
}

function SucceededSearchBy(ajaxResponse) {
    $("#Details").hide();

    $("#progressBackgroundFilter")[0].style.visibility = 'hidden';
    $("#processMessage")[0].style.visibility = 'hidden';

    $("#List").html(ajaxResponse.d).show();    
    
    $("#DataTable td:first-child").addClass("overmy");
    $("#DataTable").tablesorter({ widgets: ['zebra'] });
    /*$("#DataTable").fixedHeader({width: 940, height: 350});*/

    $("#DataTable td:first-child").attr({ title: "Click on the project ID to see the project details" });
    $("#DataTable td:first-child").click(function() { OpenProject(this.innerHTML); });
    $("#DataTable td:first-child").addClass("overmy");

    $("#SelectCombo").hide();
    //    $("#TCBreadCrumb").html("Search by <a href=''>" + $("#cboSearchBy :selected").text() + "</a> --> <a href=''>" + $("#SelectCombo :selected").text() + "</a>" + "").show("fast");
    if ($("#cboSearchBy :selected").val() != "AllProjects")
        $("#TCBreadCrumb").html("Search by <a href='javascript:ShowOption()'>" + $("#cboSearchBy :selected").text() + "</a> - " + $("#SelectCombo :selected").text()).show("fast");
    else
        $("#TCBreadCrumb").html("Search by " + $("#cboSearchBy :selected").text()).show("fast");
        

}

function ShowOption() {
    if ($("#cboSearchBy :selected").val() != "AllProjects") {
        $("#TCBreadCrumb").hide();
        $("#List").hide();
        $("#Details").hide();
        $("#SelectCombo").show();
    }
    else {
    //    $("#TCBreadCrumb").hide();
        $("#List").show();
        $("#Details").hide();
        //$("#SelectCombo").show();
    
    }
}

function ShowSelected() {
    $("#TCBreadCrumb").hide();
    $("#List").show();
    $("#Details").hide();
    $("#TCBreadCrumb").html("Search by <a href='javascript:ShowOption()'>" + $("#cboSearchBy :selected").text() + "</a> - " + $("#SelectCombo :selected").text()).show("fast");

    //$("#SelectCombo").show();
    
}


function OpenProject(id) {
    //alert(id.innerHTML);
    var itemID = { "SelectedPrj": id};
    var jsonStr = JSON.stringify(itemID);

    $("#progressBackgroundFilter")[0].style.visibility = 'visible';
    $("#processMessage")[0].style.visibility = 'visible';
    
    $.ajax({
        type: "POST",
        url: "/Web/TC/TCWebService.asmx/OpenProject",
        data: jsonStr,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: SucceededOpenProject,
        error: function(xhr, result) {
            AjaxFailed(xhr, result);
        }
    });
}

function SucceededOpenProject(ajaxResponse) {
    $("#List").hide();
    $("#Details").html(ajaxResponse.d).show();    
    $("#progressBackgroundFilter")[0].style.visibility = 'hidden';
    $("#processMessage")[0].style.visibility = 'hidden';
    $("#GoBack").attr('href', 'javascript:GoBack("List")').text("Go to Project List (" + $("#cboSearchBy")[0].value + " - " + $("#SearchBy2")[0].value + ")").show();
    if ($("#cboSearchBy :selected").val() != "AllProjects" && $("#cboSearchBy :selected").val() != "SeeProject")
        $("#TCBreadCrumb").html("Search by <a href='javascript:ShowOption()'>" + $("#cboSearchBy :selected").text() + "</a> - <a href='javascript:ShowSelected()'>" + $("#SelectCombo :selected").text() + "</a>").show("fast");
    else if ($("#cboSearchBy :selected").val() == "AllProjects")
        $("#TCBreadCrumb").html("Search by <a href='javascript:ShowOption()'>" + $("#cboSearchBy :selected").text() + "</a>").show("fast");    
    else 
        $("#TCBreadCrumb").html("Search by " + $("#cboSearchBy :selected").text()).show("fast");
        
}



//    function pageLoad() {
//        var manager = Sys.WebForms.PageRequestManager.getInstance();
//        manager.add_endRequest(endRequest);
//        manager.add_beginRequest(OnBeginRequest);
//    }

//    function OnBeginRequest(sender, args) {
//        $get('ParentDiv').className = 'Background';
//    }

//    function endRequest(sender, args) {
//        $get('ParentDiv').className = '';
//    }

function onDataFailure(error, context, methodName) {
    $("#progressBackgroundFilter")[0].style.visibility = 'hidden';
    $("#processMessage")[0].style.visibility = 'hidden';
    
    var errorMessage = error.get_message();
    $("#Err")[0].innerHTML = errorMessage;
    $("#Err")[0].className = "error";
}


function FunkyStuff() {
//		$("dd label").append(":");
    $("#headersearch")[0].style.visibility = 'hidden';
}

$(document).ready(FunkyStuff);

function checkKey(e) {
    /*$("#DataTable").tablesorter();*/
    var evt = e ? e : window.event;
    /*var bt = document.getElementById(buttonid);*/
    if (evt.keyCode == 13) {
        /*alert("enter");*/
        SearchBy('');
        return false;
    }
    else if (evt.keyCode == 8) {


        return false;
        BackSpace();
    }
}
function BackSpace() {
    return false;

}



// PageLoad function
// This function is called when:
// 1. after calling $.historyInit();
// 2. after calling $.historyLoad();
// 3. after pushing "Go Back" button of a browser
function pageload(hash) {
    // alert("pageload: " + hash);
    // hash doesn't contain the first # character.
    if (hash) {
        // restore ajax loaded state
        if ($.browser.msie) {
            // jquery's $.load() function does't work when hash include special characters like åäö.
            hash = encodeURIComponent(hash);
        }
        $("#load").load(hash + ".html");
    } else {
        // start page
        $("#load").empty();
    }
}

$(document).ready(function() {
    // Initialize history plugin.
    // The callback is called at once by present location.hash. 
   // $.historyInit(pageload, "jquery_history.html");
    $("#cboSearchBy").hide();
    // set onlick event for buttons
    /*$("a[rel='history']").click(function() {
        // 
        var hash = this.href;
        hash = hash.replace(/^.*#/, '');
        // moves to a new page. 
        // pageload is called at once. 
        // hash don't contain "#", "?"
        $.historyLoad(hash);
        return false;
    });*/
});


/*Approved*/
function DownloadDoc(id) {
    var myForm = document.createElement("form");
    myForm.method = "post";
    myForm.action = "/Web/TC/DownloadFile.aspx";
    myForm.target = $("#iframe")[0];
    var myInput = document.createElement("input")
    myInput.setAttribute("name", "id");
    myInput.setAttribute("value", id);
    myForm.appendChild(myInput);
    document.body.appendChild(myForm);
    myForm.submit();
    document.body.removeChild(myForm);
}

$(function() {
    $("#slide2 ul li a").each(function() {
        $(this).hover(function() {
            $(this).animate({ width: "600px" }, { queue: false, duration: 450 });
        }, function() {
            $(this).animate({ width: "128px" }, { queue: true, duration: 450 });
           // alert($(this).id);
        }),
        $(this).click(function() {
            $(this).animate({ width: "100px" }, { queue: false, duration: 450 });
        });
    });
});



