// A boolean value to prevent the registering of multiple begin / end request events
var eventsRegistered = false;
// Array of items to have loading effect applied too
var UpdateLoadEffectIDs = new Array();
// Array of items for location flash updates
var LocationUpdateIDs = new Array();
// Holding array so store UpdateLoadEffectIDs array
var holdingArray = new Array();

function pageLoad(sender, args){
    if (!eventsRegistered){ 
        // register our events
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
        eventsRegistered = true;
    }
} 

function beginRequest(sender, args){
    // Save the Array of IDs to an holding array for restoration after the postback has completed
    holdingArray = UpdateLoadEffectIDs.slice();
    
    //alert(args.get_postBackElement().id);
    
    // Get the postback initiater
    var initID = args.get_postBackElement().id;
    
    //alert(initID);
    
    // Set the default rows selcted value
    var ArrayRowSelected = -1;
    
    // This checks if the initiater of the async postback is in UpdateLoadEffectIDs array, we
    // only post back via the panel for pagination change, hence only apply load effect to that panel
    for(var i=0; i<UpdateLoadEffectIDs.length; i++){
        if (UpdateLoadEffectIDs[i][2] == initID){
            ArrayRowSelected = [i];
        }
    }
    
    // If we are only applut loading effect to 1 panel filer the rest from UpdateLoadEffectIDs array
    if (ArrayRowSelected >= 0){
        var tempArray = new Array();
        tempArray[0] = UpdateLoadEffectIDs[ArrayRowSelected].slice();;
        UpdateLoadEffectIDs.length = 0;
        UpdateLoadEffectIDs[0] = tempArray[0].slice();
        tempArray = null;
    }
    
    // Display the update panels & loader images contained in the array
    for(var i=0; i<UpdateLoadEffectIDs.length; i++){
        $get(UpdateLoadEffectIDs[i][0]).style.display = '';
        $get(UpdateLoadEffectIDs[i][1]).style.display = '';
    } 
 
    // Position the load effect panels
    for(var i=0; i<UpdateLoadEffectIDs.length; i++){
        // Get eh panels to apply effects too
        var _updateProgressDiv = $get(UpdateLoadEffectIDs[i][0]);     
        var _backgroundDiv = $get(UpdateLoadEffectIDs[i][1]);
        var _searchPanel = $get(UpdateLoadEffectIDs[i][2]);
       
        // get the bounds of both the updatepanel and the progress div
        var UpdatePanelBounds = Sys.UI.DomElement.getBounds(_searchPanel);
        var updateProgressDivBounds = Sys.UI.DomElement.getBounds(_updateProgressDiv);
                
        //  set the dimensions of the background div to the same as the updatepanel
        _backgroundDiv.style.width = UpdatePanelBounds.width + 'px';
        _backgroundDiv.style.height = UpdatePanelBounds.height + 'px';

        //  center of updatepanel
        var x = UpdatePanelBounds.x + Math.round(UpdatePanelBounds.width / 2) - Math.round(updateProgressDivBounds.width / 2);
        var y = UpdatePanelBounds.y + Math.round(UpdatePanelBounds.height / 2) - Math.round(updateProgressDivBounds.height / 2); 

        //  set the progress element to this position
        Sys.UI.DomElement.setLocation(_updateProgressDiv, x, y);
 
        //  place the div over the updatepanel
        Sys.UI.DomElement.setLocation(_backgroundDiv, UpdatePanelBounds.x, UpdatePanelBounds.y); 

        // Get the Bounds & x value of the Progress panel again now the overlay has been set and apply x location
        updateProgressDivBounds = Sys.UI.DomElement.getBounds(_updateProgressDiv);
        x = UpdatePanelBounds.x + Math.round(UpdatePanelBounds.width / 2) - Math.round(updateProgressDivBounds.width / 2);
        Sys.UI.DomElement.setLocation(_updateProgressDiv, x, y);
    }
}

// Turn of the loading panels after postback has finished
function endRequest(sender, args) {
    for(var i=0; i<UpdateLoadEffectIDs.length; i++){
        _updateProgressDiv = $get(UpdateLoadEffectIDs[i][0]);
        _backgroundDiv = $get(UpdateLoadEffectIDs[i][1]);
        _updateProgressDiv.style.display = 'none';
        _backgroundDiv.style.display = 'none';
    } 
    // restore the ID's array from the holding array and empty the holding array   
    UpdateLoadEffectIDs = holdingArray.slice();
    holdingArray.length = 0;
}

// code to find flash movie
function getFlashObj(movie) {
    alert("getFlashObj called");
    if (window.document[movie]) {
        return window.document[movie];
    }
    if (navigator.appName.indexOf("Microsoft Internet") == -1) {
        if (document.embeds && document.embeds[movie]) {
            return document.embeds[movie];
        }
    } else {
        return document.getElementById(movie);
    }
}

// standard interface for Flash calls on JavaScript
function javascriptInterface(jObj)
{
	//window.alert("Call made by Flash, command: " + jObj.command + ", returnRequired: " + jObj.returnRequired + ", parameters: " + jObj.params + ", webtrends: " + jObj.analytics);	
	switch(jObj.command)
	{	
		case "page_available":
		return true;
		break;
		
		case "flash_available":
		FadeIn('ajax-panel')
		return true;
		break;
		
		case "map_update":
		//var RegionCommand = GetCMSRegion(jObj.params[0]);
		FlashRegionChanged(jObj.params)
		break;
		
		default:
		return false;
	}
}


function FlashRegionChanged(params)
{
    var regionID = params[0];
    var zoomLevel = parseInt(params[1]);
    
    for(var i=0;i<LocationUpdateIDs.length;i++){
        var RegionHF = document.getElementById(LocationUpdateIDs[i][0]);
        var SubRegionHF = document.getElementById(LocationUpdateIDs[i][1]);
        if (zoomLevel < 1){
            RegionHF.value = "";
            SubRegionHF.value = "";
            __doPostBack(LocationUpdateIDs[i][0],"");
        }
        else if (zoomLevel == 1){
            RegionHF.value = GetCMSRegion(regionID);
            SubRegionHF.value = "";
            __doPostBack(LocationUpdateIDs[i][0],"");
        }
        else if (zoomLevel > 1){
            SubRegionHF.value = GetCMSSubRegion(regionID);
            if (LocationUpdateIDs[i][1] != null){
                __doPostBack(LocationUpdateIDs[i][1],"");
            }
        }
    }
}

// Map the region string from flash to the CMS value
function GetCMSRegion(regionString)
{
    var CMSregionName = ""   
    switch(regionString)
    {
        case "shropshire":
        CMSregionName = "Shropshire";
        break;
          
        case "herefordshire":
        CMSregionName = "Herefordshire";
        break;
                  
        case "worcestershire":
        CMSregionName = "Worcestershire";
        break;
            
        case "warwickshire":
        CMSregionName = "Warwickshire";
        break;
 
        case "black_country":
        CMSregionName = "The Black Country";
        break;
        
        case "staffordshire":
        CMSregionName = "Staffordshire";
        break;
        
        case "telford":
        CMSregionName = "Telford & Wrekin";
        break;

        case "stoke_on_trent":
        CMSregionName = "Stoke-on-Trent";
        break;
        
        case "black_country":
        CMSregionName = "The Black Country";
        break;
        
        case "birmingham":
        CMSregionName = "Birmingham";
        break;
        
        case "solihull":
        CMSregionName = "Solihull";
        break;
        
        case "coventry":
        CMSregionName = "Coventry";
        break;
        
        default:
        CMSregionName = "";
        break;
    }    
    return CMSregionName;
}

// Map the region string from flash to the CMS value
function GetCMSSubRegion(subRegionString)
{
    var CMSregionName = ""   
    switch(subRegionString)
    {
        case "bridgenorth":
        CMSregionName = "Bridgnorth";
        break;
        
        case "bromsgrove":
        CMSregionName = "Bromsgrove";
        break;
        
        case "cannock_chase":
        CMSregionName = "Cannock Chase";
        break;
        
        case "dudley":
        CMSregionName = "Dudley";
        break;
        
        case "east_staffordshire":
        CMSregionName = "East Staffordshire";
        break;
        
        case "lichfield":
        CMSregionName = "Lichfield";
        break;
        
        case "malvern_hills":
        CMSregionName = "Malvern hills";
        break;
        
        case "newcastle_under_lyme":
        CMSregionName = "Newcastle-under-Lyme";
        break;
        
        case "north_shropshire":
        CMSregionName = "North Shropshire";
        break;
        
        case "north_warwickshire":
        CMSregionName = "North Warwickshire";
        break;
        
        case "nuneaton":
        CMSregionName = "Nuneaton & Bedworth";
        break;
        
        case "oswestry":
        CMSregionName = "Oswestry";
        break;
        
        case "redditch":
        CMSregionName = "Redditch";
        break;
        
        case "rugby":
        CMSregionName = "Rugby";
        break;
        
        case "sandwell":
        CMSregionName = "Sandwell";
        break;
        
        case "shrewsbury":
        CMSregionName = "Shrewsbury & Atcham";
        break;
        
        case "south_shropshire":
        CMSregionName = "South Shropshire";
        break;
        
        case "south_staffordshire":
        CMSregionName = "South Staffordshire";
        break;
        
        case "stafford":
        CMSregionName = "Stafford";
        break;
        
        case "staffordshire_moorlands":
        CMSregionName = "Staffordhire Moorlands";
        break;
        
        case "stratford":
        CMSregionName = "Stratford-on-Avon";
        break;
        
        case "tamworth":
        CMSregionName = "Tamworth";
        break;
        
        case "walsall":
        CMSregionName = "Walsall";
        break;
        
        case "warwick":
        CMSregionName = "Warwick";
        break;
        
        case "wolverhampton":
        CMSregionName = "Wolverhampton";
        break;
        
        case "worcester_city":
        CMSregionName = "Worcester city";
        break;
        
        case "wychavon":
        CMSregionName = "Wychavon";
        break;
        
        case "wyre_forest":
        CMSregionName = "Wyre Forest";
        break;
       
        default:
        CMSregionName = "";
        break;
    }    
    return CMSregionName;
}

function ReWriteLinks(ContainerEl, hfToUpdate, ctrlToPost)
{
    var PagContainer = document.getElementById(ContainerEl);
    try
    {
        var Links = PagContainer.getElementsByTagName('a');
        var unknown; 
        
        for(var i=0;i<Links.length;i++){
            if (Links[i].getAttribute('href') != null) {
                    //Links[i].removeAttribute('href');
                    Links[i].setAttribute('href', '#x');
                    Links[i].setAttribute('rel', Links[i].innerHTML);
                    Links[i].onclick=function() { 
                    AjaxPageChanged(this.rel, hfToUpdate, ctrlToPost);
                }
            }
        } 
    }
    catch(err)
    {
        //alert(err + " - This is casued by the link re-writer, there are no links to find in the paramater element");
    }
}

function AjaxPageChanged(command, hfToUpdate, pnlToPost)
{
   var obj = document.getElementById(hfToUpdate);
   obj.value = command;
   __doPostBack(pnlToPost,"");
}

function FadeIn(element){
    var Panel = document.getElementById(element)
    var FadeIn = new Fx.Tween(Panel, {duration: 'long'});
    FadeIn.start('opacity', '0', '1');
}

function initSlide(SlideWidth, ResultsPanelID, PevBtnID, NxtBtnID, CurrentPageTxtID) {
        var panelWidth = parseInt(SlideWidth);
	    var currentPos = $get(ResultsPanelID);
	    var CurrentPageText = document.getElementById(CurrentPageTxtID)
	    var Container = document.getElementById(ResultsPanelID)
	    var moveSlider = new Fx.Tween(Container, {duration: 'short'},{link: 'ignore'});
		var currentPosRight = parseInt(currentPos.getStyle('right').replace(/px/, ""));
		var currentPosWidth = parseInt(currentPos.getStyle('width').replace(/px/, ""));
	    
	    Container.getElementsByTagName('div')[0].getElementsByTagName('div')[0].className = 'search-results-item-inner-focus';

        // Set the initial state of the prev / next buttons
        //$(PevBtnID).className = "previousbtn inactive";
        if (currentPosWidth == panelWidth){
            $(NxtBtnID).className = "nextbtn inactive";
        }


	    $(PevBtnID).addEvent('click', function(){																																		
		    currentPosRight = parseInt(currentPos.getStyle('right').replace(/px/, ""));
		    if ((currentPosRight >= panelWidth) && ((currentPosRight % panelWidth) == 0))
		    {
		        var CurrentNumber = parseInt(CurrentPageText.innerHTML);
		            try {
			            Container.getElementsByTagName('div')[((CurrentNumber - 1) * 2)].getElementsByTagName('div')[0].className = 'search-results-item-inner';
			        }
			        catch(Error)
			        {}
			        moveSlider.start('right', (currentPosRight - panelWidth)).chain(function(){
			        CurrentPageText.innerHTML = (CurrentNumber - 1);
			        try {
			            Container.getElementsByTagName('div')[((CurrentNumber - 2) * 2)].getElementsByTagName('div')[0].className = 'search-results-item-inner-focus';
			        }
			        catch(Error)
			        {}
			        $(NxtBtnID).className = "nextbtn";
			        if (currentPosRight == panelWidth){
		                $(PevBtnID).className = "previousbtn previousinactive";
		            }
			    });
		    }						
	    });
    	
	    $(NxtBtnID).addEvent('click', function(){																																		
		    currentPosRight = parseInt(currentPos.getStyle('right').replace(/px/, ""));
		    if (currentPosRight <= (containerWidth - (panelWidth * 2)) && ((currentPosRight % panelWidth) == 0))
		    {
	            var CurrentNumber = parseInt(CurrentPageText.innerHTML);
	            try {
		                Container.getElementsByTagName('div')[((CurrentNumber - 1) * 2)].getElementsByTagName('div')[0].className = 'search-results-item-inner';
		            }
		            catch(Error)
		            {}
		            moveSlider.start('right', (currentPosRight + panelWidth)).chain(function(){
		            CurrentPageText.innerHTML = (CurrentNumber + 1);
		            try {
		                Container.getElementsByTagName('div')[((CurrentNumber) * 2)].getElementsByTagName('div')[0].className = 'search-results-item-inner-focus';
		            }
		            catch(Error)
		            {}
		            $(PevBtnID).className = "previousbtn";
		            if ((currentPosRight + (panelWidth * 2)) == currentPosWidth){
	                    $(NxtBtnID).className = "nextbtn inactive";
	                }
		        });	
		    }
        });
}