﻿// JScript File for supporting Champions based content

// utility functions
function ReloadOnSave(res)	{
	var result = res.value,
		listTokens = result.split('|');
					
	if (listTokens[0] == '0') {
		alert(listTokens[1]);
		this.UpdateAjaxSessionTimer();
	}
	else	{
		 location.reload();
	}
 }

function ShowFeatureSection(sectionName)	{
    $("#main-nav li").removeClass('selected');
    $("#main-nav li." + sectionName).addClass('selected');
    $(".champTab").hide();
    $("div." + sectionName).show();
}

function EditChampEmployer(id)	{
    Place(ChampionFeatureControl.FireEditChampEmployer(id));     
    $(function (){ $('.champEdit').show(); });     
}

function ReloadChampEmployer(champID)	{
   var res = ChampionFeatureControl.FireReloadEmployer(champID);
   Place(res);
   $(function (){ $('.champEdit').show(); });    
}

function SaveChampEmployer(champID)	{
       var json = GetJSONForSection('#featuredEmp');
       ChampionFeatureControl.FireJsonSave(champID, json);  
       ReloadChampEmployer(champID);
}

function EditChampJob(id)	{
    Place(ChampionFeatureControl.FireEditChampJob(id));     
    $(function (){ $('.champEdit').show(); });     
}

function ReloadChampJob(champID)	{
   var res = ChampionFeatureControl.FireReloadJob(champID);
   Place(res);
   $(function ()	{ 
		$('.champEdit').show(); 
	});    
}

function SaveChampJob(champID)	{
       var json = GetJSONForSection('#featuredJob');
       ChampionFeatureControl.FireJsonSave(champID, json);  
       ReloadChampJob(champID);
}
// Utility End

function ReloadChampQandA(champID)	{
   var res = ChampionFeatureControl.FireReloadQandA(champID);
   Place(res);
   $(function ()	{ 
		$('.champEdit').show(); 
	});    
}

function EditChampQandA(id)	{
    Place(ChampionFeatureControl.FireEditChampQandA(id));
    $(function ()	{
		$('.champEdit').show();
	});
}

function SaveChampQandA(champID)	{
       var json = GetJSONForSection('#QandA');
       //ChampionFeatureControl.FireJsonSave(champID, json);
       //need specialist save method but can handily use the json to do it.
       ChampionFeatureControl.FireSaveQandA(champID, json);
       ReloadChampQandA(champID);
}

function ChangedTOB()	{
    if (GetSelectedOptionValue('p_TypeOfBusiness') === '11' || GetSelectedOptionValue('p_TypeOfBusiness') === '12')	{
        $('#OtherBusiness').show();
    }	else	{
        $('#OtherBusiness').hide();
    }
}

function EditChampMainDetails(id)   {
    Place(ChampionControl.FireEditMain(id));   
    $(function ()	{ 
		$('.champEdit').show(); 
	});
}

function EditChampSideDetails(id)	{
    Place(ChampionControl.FireEditSide(id));   
    $(function ()	{ 
		$('.champEdit').show(); 
	});
    ChangedTOB();
}

function ChampSelected(item) {
    var champID = item.id;
    if (champID > 0)	{
        location.href = 'Champion.aspx?id=' + champID;
    }
}

function SearchAll()	{
    $('#suggestBox')[0].value='**';
    runSuggest.apply($('#suggestBox')[0]);
    $('#suggestBox')[0].value='';
}

function SaveChampDetails(divToSave, recordId)	{
   var json = GetJSONForSection(divToSave);
   ReloadOnSave(ChampionControl.FireJsonSave(recordId, json));  
}

function RebuildChampionDetails()	{
    location.reload();
}

// Message Board functions
function ReloadBoard(champID, page)	{
    if ($('#srchMessages').length > 0)	{
        var srch = Value('srchMessages');
        ChampionFeatureControl.FireReloadMessageBoard(champID, srch, page, function (res)	{
            Place(res);
            $('#srchMessages')[0].value = srch;
        });
    }	else	{
        ChampionFeatureControl.FireReloadMessageBoard(champID, '', page, Place);
    }
}

function GetPage()	{
	var page = 0;
    if ($('#CurrentPage').length > 0)	{
        page = parseInt($('#CurrentPage').text(), 10) -1;
    }
    return page;
}

function SaveMessage(champID, msgID)	{
    var txt = Value('newMsgText');
    var page = GetPage();
    ChampionFeatureControl.FireSaveMessage(champID,msgID, txt);
    ReloadBoard(champID,page);
}

function PostNewMessage(champID)	{
    Place(ChampionFeatureControl.FireShowPostNewMessage(champID));
}

function EditMessage(champID,msgID)	{
   Place(ChampionFeatureControl.FireEditMessage(champID, msgID));
}

function DeleteMessage(champID,msgID)	{
    if (confirm('Please confirm you wish to delete this message'))	{
        var result = ChampionFeatureControl.FireDeleteMessage(champID, msgID).value,
			listTokens = result.split('|');
	    if (listTokens[0] == '0')	{
		    alert(listTokens[1]);
	    }	else	{
		    ReloadBoard(champID,0);
	    }
	}
}

function ReplyToMessage(msgID)	{
    Place(ChampionFeatureControl.FireShowPostNewReply(msgID));
}

function SaveReply(champID, msgID, replyID)	{
    var page = GetPage();
    var txt = Value('newMsgText');
    ChampionFeatureControl.FireSaveReply(champID,msgID,replyID, txt);
    ReloadBoard(champID,page);
}

function EditReply(champID, msgID)	{
    Place(ChampionFeatureControl.FireEditReply(champID, msgID));
}

function ClearAdressFields()    {
    $('#fAddress1, #fAddress2, #fTown, #fCounty, #fCountry, #fPostcode').val('');
}

function RegisterNewChamp(bType)
{
	if (!CheckTerms()) {
		alert('You must agree with the sites terms and conditions before you can register.');
		return;
	}

    SpinMe(MyObject('registerNewUserButtonWait'), "<strong>Creating Your Account, please wait...</strong>");

	// Get details
	var sFirstName = $('#fYourName').val(),
	    sLastName = $('#fLastName').val(),
	    sChampName = $('#fChampName').val(),
	    sChampID = $('#fChampID').val(),
	    sEmail = $('#fEmail').val(),
	    sPassword1 = $('#fPassword1').val(),
	    sPassword2 = $('#fPassword2').val(),
	    bOption = $('#fOptin').is(':checked'),
	    bOptionThirdParty = $('#fOptinThirdParty').is(':checked'),
	    bOptionEmailPref1 = $('#fOptinEmaiPref1').is(':checked'),
	    bOptionEmailPref2 = $('#fOptinEmaiPref2').is(':checked'),
	    bOptionEmailPref3 = $('#fOptinEmaiPref3').is(':checked'),
        sAddress1 = $('#fAddress1').val(),
        sAddress2 = $('#fAddress2').val(),
        sAddress3 = $('#fTown').val(),
        sAddress4 = $('#fPostcode').val(),
        sAddress5 = $('#fCounty').val(),
        sAddress6 = $('#fCountry').val(),
        sMobile = $('#fMobile').val(),
        sWebsite = $('#fWebsite').val(),
        sChampType = $('#organisationType').val(),
        sChampFurtherInfo = "",
        pathwayIDs = [];
        
    $(".PathwayCheckBox:checked").each(function (i) 
    {
        pathwayIDs.push(this.id.substr(4));                
    });
    
    if (sChampType === "-1")    {
        alert('You must select the type of champion you are!');
        UnSpinMe(MyObject('registerNewUserButtonWait'));
        return false;
    }
    
    if (parseInt(sChampType, 10) < 4)   {
        var sInstType = undefined;
        switch(parseInt(sChampType, 10))    {
                case 0:
                    sInstType = "School"; 
                    break;
                case 1:
                    sInstType = "College"; 
                    break;
                case 2:
                    sInstType = "University";
                    break;
                case 3:
                    sInstType = "Company";
                    break;
        }
    
        if ($('#CollegeNameResults').val() === "0") {
        
            alert('Please tell us what ' + sInstType + ' you are from.');
            UnSpinMe(MyObject('registerNewUserButtonWait'));
            return false;
        }
        else    {
            sChampFurtherInfo = $('#CollegeNameResults').val()
            if (sChampFurtherInfo === "-1") {
                if($('#fUnlistedCollege').val() === "") {
                    alert('Please provide us a name for your ' + sInstType);
                    UnSpinMe(MyObject('registerNewUserButtonWait'));
                    return false;
                }
                else    {
                   sChampFurtherInfo = sChampFurtherInfo + "|" + $('#fUnlistedCollege').val();
                }
            }
        }
    }
    else if (parseInt(sChampType, 10) > 10)   {
        if ($('#furtherInfo').val() === "") {
            alert('Please provide us with some further information about your organisation.');
            UnSpinMe(MyObject('registerNewUserButtonWait'));
            return false;
        }
        else    {
            sChampFurtherInfo = $('#furtherInfo').val();
        }
    }
	RegisterChampionControl.RegisterNewChamp(sFirstName, sLastName, sChampName, sChampID, sEmail, sPassword1, sPassword2, bOption, bOptionThirdParty, sAddress1, sAddress2, sAddress3, sAddress4, sAddress5, sAddress6, sMobile, sWebsite, sChampType, sChampFurtherInfo, bOptionEmailPref1, bOptionEmailPref2, bOptionEmailPref3, pathwayIDs, CallBack_RegEmployer);					
}

function Reg_FillInAddressDetails(bShort)   {
    /* **Note** bShort is a bit of a bodge, it is an unecisserry variable to be passed in, but the old code that 
    produces the call puts it in.*/
    var sOID = $('#CollegeNameResults').val();
    
    $('#AutoFillMsg').remove();
    
    if (sOID === "-1")   {
        ClearAdressFields();
        $('#fPostcode').attr('disabled', false);
        $('#PostcodeSearch').show();
        $('#NoUKPostCodeSpan').show();
        $('#CollegeNameNotListed').show();
    }
    else    {
        $('#CollegeNameNotListed').hide();
        ClearAdressFields();
    
        RegisterChampionControl.GetAddressFromPoLOID(sOID, function(res)    {
            if (res.value === "")    {
                alert('Could not find address details for this institution, please fill in the address details manually.');
                ClearAdressFields();
                $('#fPostcode').attr('disabled', false);
                $('#PostcodeSearch').show();
                $('#NoUKPostCodeSpan').show();
            }
            else    {
                $('#fPostcode').attr('disabled', true);
                $('#PostcodeSearch').hide();
                $('#NoUKPostCodeSpan').hide();
                $('#NoUKPostCodeSpan').after('<span id="AutoFillMsg">Address Details have been auto filled from your selection.</span>');
                
                var arrAddressParts =  res.value.split('|');
                for (var s in arrAddressParts) {
                    if (arrAddressParts.hasOwnProperty(s)) {
                        var aParts = arrAddressParts[s].split(':');
                        
                        $('#' + aParts[0]).val(aParts[1]);
                    }
                }
            }
        });
    }
}

function ChampReg_TypeOBussinessChange(sParam)    {
    var shortVersion = false,
        sOrgType = undefined,
        bNeedToWait = false;
    
    if (typeof sParam === 'undefined')  {
        sOrgType = $('#organisationType').val();
    }
    else if (sParam === 'short')  {
        shortVersion = true;
    }
    else    {
        sOrgType = sParam
        bNeedToWait = true;
    }

    if (sOrgType == "0" || sOrgType == "1" || sOrgType == "2" || sOrgType == "3")
    {
        $("#champname").hide();
        
    }
    else if (sOrgType == "4")
    {
        $("#champname").hide();
      
    }
    else
        $("#champname").show();
        
    ClearAdressFields();
    $('#fPostcode').attr('disabled', false);
    $('#PostcodeSearch').show();
    $('#NoUKPostCodeSpan').show();
    $('#CollegeNameNotListed').show();
    $("#SectorSection").hide();
    if (!bNeedToWait)   {
    SpinMe($("#extraInfoDiv").get(0), "Loading...");
        RegisterChampionControl.GetExtraInfoHTML(sOrgType, shortVersion, function(res) {
            $("#extraInfoDiv").html(res.value);
            UnSpinMe($("#extraInfoDiv").get(0));    
        });
    }
    else
    {
        var res = RegisterChampionControl.GetExtraInfoHTML(sOrgType, shortVersion);
        $("#extraInfoDiv").html(res.value);
    }
}

function CheckForExistingChamps()   {
    $('.existingChampDiv').hide();
    
    
    if ($('#fChampName').val().length <= 2)    {
        return false;
    }
    else    {
        var sChampName = $('#fChampName').val(),
            iRandom = Math.floor(Math.random()*1000)
        
        if ($('.loadingMessage').length !== 0)  {
            $('.loadingMessage').attr('id', "i" + iRandom);
        }
        else    {
            $('.existingChampDiv').after('<span id="i' + iRandom + '" class="loadingMessage"><img src="images/ajax-loader.gif" />&nbsp;Checking for existing Champions...</span>')
        }
        
        $('.existingChampDiv').attr('id', "d" + iRandom);
        setTimeout(function() {
            if($('#fChampName').val() === sChampName)   {
                RegisterChampionControl.GetChampListFromName(sChampName, function(res)  {
                    var sChampList = res.value.split('|'),
                        sHTML = "";
                    
                    if (sChampList.length === 1 && sChampList[0] === "")    {
                        $('#i' + iRandom).html('<span class="RoundedMsg">None Found</span>').fadeTo(2000, 1, function()    {
                            $('#i' + iRandom).fadeOut('slow', function()   {
                                $('#i' + iRandom).remove();
                            });
                        }); 
                        return false;
                    }
                    else    {
                        for (var i in sChampList) {
                            if (sChampList.hasOwnProperty(i)) {
                                var aParts = sChampList[i].split(':');
                                
                                sHTML = sHTML + '<span onclick="SetRegesteringChampTo(' + aParts[1] + ');">' + aParts[0] + '</span>';
                            }
                        }
                    }
                    $('#i' + iRandom).remove();
                    $('#existingChampList').html(sHTML);
                    $('#d' + iRandom).show();
                    
                });
            }
        }, 2000);
    }
}

/*True for Disable, false for enable.*/
function DisableChampionSpecificFields(bDisableOrEnable)    {
    if (typeof bDisableOrEnable === 'undefined')    {
        bDisableOrEnable = true;
    }
    $('#fChampName,#organisationType,#CollegeNameResults,#CollegeNameNotListed,#fPostcode').attr('disabled', bDisableOrEnable);
    $('#fMobile,#fWebsite, #fUnlistedCollege, #PathwaysList input').attr('disabled', bDisableOrEnable);
    
    if (bDisableOrEnable)   {
        $('#PostcodeSearch').hide();
        $('#NoUKPostCodeSpan').hide();
    }   
    else    {
        $('#PostcodeSearch').show();
        $('#NoUKPostCodeSpan').show();
    }
}

function ClearChampionSpecificFields()  {
    $('#fChampName,#fPostcode,#fAddress1,#fAddress2,#fTown,#fCounty,#fMobile,#fWebsite,#fChampID').val('');
    $('#extraInfoDiv').html('');
    $('#CollegeNameNotListed').hide();
    $('#organisationType').val('-1').change();
    
    $('#PathwaysList input').attr('checked', false);
}

function ClearChampChoice() {
    ClearChampionSpecificFields();
    DisableChampionSpecificFields(false);
    $('#fChampName').css('width', '98%')
    $('#ClearChampSelectionMsg').remove();
}

function SetRegesteringChampTo(sOID)    {
    $('#existingChampList').html('<span class="loadingMessage"><img src="images/ajax-loader.gif" />&nbsp;Loading... Please Wait.</span>');
    
    RegisterChampionControl.GetChampInfoFromOID(sOID, function(res) {
        if (res.value === "") {
            alert('There was a problem finding the champion you clicked? Please refresh the page and try again.');
        }
        else    {
            var sJSON = res.value;
	        dic = JSON.parse(sJSON);
	        
	        if (dic.hasOwnProperty('#organisationType')) {
                ChampReg_TypeOBussinessChange(dic['#organisationType']);
                
                if (dic.hasOwnProperty('#CollegeNameResults'))  {
                    if (dic['#CollegeNameResults'] === "-1")   {
                        ClearAdressFields();
                        $('#fPostcode').attr('disabled', false);
                        $('#PostcodeSearch').show();
                        $('#NoUKPostCodeSpan').show();
                        $('#CollegeNameNotListed').show();
                    }
                }               
	        }
	        
	        FillInPageInputsFromJson(sJSON);
	        
	        DisableChampionSpecificFields();
	        
	        $('#fChampName').css('width', '230px').before('<span id="ClearChampSelectionMsg"><a href="#" onclick="ClearChampChoice();return false;">Cancel Selection</a></span>');
            $('#existingChampList').html('<span class="DoneMsg">Done!!</span>');
            $('.existingChampDiv').fadeTo(2000, 1, function()   {
                $('.existingChampDiv').fadeOut('slow');
            });
        }
    });
}

function SendChampionEditRightsRequest()    {
    $('#EditRightsLink').html('<span class="loadingMessage"><img src="images/ajax-loader.gif" />&nbsp;Loading... Please Wait.</span>');
    ChampionControl.SendChampionEditRequest(function(res)  {
        $('#EditRightsLink').html(res.value.split('|')[1]);
    });
}

/*******************************
 *JP 03/08/09
 ********************************
 *
 * A function that will take a Dictionary that has been seralised and passed back to JS containing the hey as the element selector, and value as when you want
 * to set it to and will fill out the page.
 *
 * *Notes:
 *    In the case of a checkbox, pass the string value of "true" into the dictionary to check it, else it will uncheck it.
 *    In the case of Select Boxes pass in the value fo the option you want selected.
 *    In the case of an HTML Element, just pass in the selector and the HTML.
 *    In the case of an Text Box, just pass in the selector and the value you want to set it to.
 *
 * *Limitations:
 *    Not yet implemented anything to do with multi select boxes.
 *    Not Yet looked at Text Areas..
**************************************/
function FillInPageInputsFromJson(sJSON)   {
    dic = JSON.parse(sJSON);
    	    
    for(element in dic) {
        if (dic.hasOwnProperty(element))    {
            if ($(element).length !== 0)    {
                if ($(element).get(0).type === "checkbox")    {
                    if (dic[element] === "true")    {
                        $(element).attr('checked', true);  
                    }
                    else    {
                        $(element).attr('checked', false);
                    }
                }
                else if ($(element).get(0).type === "text" || $(element).get(0).type === "select-one")  {
                    $(element).val(dic[element]);
                }
                else    {
                    alert('Element ' + element + ' Has been presumed HTML');
                    $(element).html(dic[element]);
                }
            }
            else    {
                alert('Could not find the element: ' + element);
            }
        }
    }
}