var FADE_SPEED = 'normal';
var isFlashReady = false;
var isPossibleRefresh = true;
var fixFlashTimeout;
function debug(str) {
			var isDebug = $("#isdebug").val()
			if(isDebug == "true"){
				$("#requestLink").show();
      	$('body').append("<p>"+str+" (" + new Date() + ")</p>");
    	} else {
    		$("#requestLink").hide();
    	}
}


function checkSearchEnter(e){ //e is event object passed from function invocation
    var characterCode //literal character code will be stored in this variable

    if (e && e.which) { //if which property of event object is supported (NN4)
        e = e
        characterCode = e.which //character code is contained in NN4's which property
    } else { 
        e = event
        characterCode = e.keyCode //character code is contained in IE's keyCode property
    }

    if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
        //document.forms[0].submit() //submit the form
        doSearch();
        return false
    } else {
        
        return true
    }
}

function isReady() {
    debug('flash ready at ' + new Date());
    isFlashReady = true;
    //alert(thisMovie("Masterbuilders3").test());
	return true;
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName]
    }
    else {
        return document[movieName]
    }
}

function flashAlert(str) {
    alert(str);
}

function flashGoto(destination,source,dst,isDecodeNeeded) {
    if (isDecodeNeeded == null) {
        isDecodeNeeded = false;
    }
    if (isDecodeNeeded) {
        dst = queryParamsToObj(dst);
    }
    destination = destination + "";
    source = source + "";
    debug('flashGoto ' + dst.page + ',' + source + ',' + isDecodeNeeded);
    var success = false;
    
    if (isFlashReady) {
        //document.form2.externalCalls.options.add(new Option(destination + " / " + param),0);
        //debug("calling movie with " + dst.page + "/" + source);
        try {
            thisMovie("Masterbuilders3").goto(dst,source);
            success = true
        } catch (err) {
            //dont do anything, just try later
            debug("caught error calling flash movie with " + dst.page + ", " + source + " : " + err + "," + err.description);
        }
    }
    if (!success) {
        debug('set timeout for ' + destination);
        //try again in 100 ms
//        debug(document.location.hash)
        var hash = document.location.hash;
        hash = hash.replace(/#/g,'')
        setTimeout('flashGoto("' + destination + '","' + source + '","' + hash + '",true)',1000);
    }
}
/*
function requestJSON(page,param) {
    switch(type) {
        case 'village':
            $.getJSON("/json/VillageDetailJSON.aspx?v="+param, function(json){
              alert("JSON Data: " + json);
            });
        break;
}
*/



function initStateManager() {
	//debug('start');
	var hash = document.location.hash;
	//debug('1');
    hash = hash.replace(/#/g,'')
    //debug('2');
    //document.form1.source.value = hash;    
	window.StateManager = EXANIMO.managers.StateManager;
	//debug('3');
	//StateManager.setState2 = StateManager.setState;
	StateManager.onstatechange = function(e)
	{	
	    debug('stateChangeHandler(' + e.id + ')');
	    //StateManager.setTitle('TO ' + e.id + ' FROM ' + document.form1.source.value);
	    //alert('source was ' + document.forms[0].source.value);
	    GoTo(e.id,document.forms[0].source.value);
	    //postBackHiddenField(e.id);
	    //alert(e.id);
	    document.forms[0].source.value = e.id;
	}
	//debug('4');
	if (document.location.hash == '' || document.location.hash == '#') {
		debug('5.. ack');
		//setStateNow('page=homepage'); //doesnt work on initial load in firefox
		//document.location.hash = 'page=homepage';
		setStateNow("page=homepage");
	} 
	//alert('6' + document.location.hash);
}

function setStateNow(state) {
    isPossibleRefresh = false;
    temp = new Date();
	StateManager.setState(state + '&refresh=' + temp.getTime() );
	//StateManager.setState(state);
}

var SEARCH_DEFAULT = 'Search';


function doSearch() {
   if (document.forms[0].searchWord.value != SEARCH_DEFAULT && document.forms[0].searchWord.value != "") {
		//var type = document.forms[0].type.options[document.forms[0].type.selectedIndex].value;
		var text = document.forms[0].searchWord.value;
		//setStateNow('page=search&type='+type+'&string=' + text);
		setStateNow('page=search&string=' + text);
	}
}

function setLoadingPanel(id) {
	//display a temporary loading gif while the content loads	
	var el = document.getElementById(id);
	el.innerHTML = '&nbsp;';
	el.className = 'loading';
	
	
	
}


function queryParamsToObj(params) {
	
	//takes a query string (name=value&name2=value) and converts it to an object
	var obj = new Object();
	var pairs = params.split('&');
	for (var i=0;i<pairs.length;i++) {		
		pair = pairs[i].split('=');
		if (pair.length>1) {
			obj[pair[0]] = pair[1]			
		}
	}
	return obj;	
}


/*function defaultToHomePage() { //deprecated??
	alert('defaultToHomePage()');
	//defaults to hiding the lower panel so that deep links do not show the home page before updating... may be possible to remove once the loader image is implemented
	if (document.location.hash == '' || document.location.hash == '#') {
		//todo: find out why this isn't displaying the hash in the browser, and if its a problem. (it works to show the page)
		alert('set state');
		setStateNow('page=homepage');
	} 
}*/

function GoTo(gotoDestination,gotoSource) {
    if (gotoDestination == gotoSource && !isPossibleRefresh) {
        debug("cancelled GoTo: duplicate request detected");
        return;
    }

  //postBackHiddenField(

  //var source=document.form1.source.value;
  if (gotoSource == "") { 
    gotoSource = "page=firstview&id=0";
  }
  var src = queryParamsToObj(gotoSource);
  var dst = queryParamsToObj(gotoDestination);
  //src = queryParamsToObj(e.id);
  //dst = queryParamsToObj(document.form1.source.value);
	    
  //from source to destination
  /*
  destinations:
  village vid
  
  goto('village&vid=1')
  house hid vid 
  goto('house&vid=1&hid=1')
    - can lookup village from it if loading the page fully but might as well provide village id
  room rid hid vid
  goto('room&rid=1&hid=1&vid=1')
  showcase product pid rid hid vid
  goto('showcaseproduct&pid=1&rid=1&hid=1&vid=1')
  supplier sid pid rid hid vid
  goto('showcasesupplier&pid=1&rid=1&hid=1&vid=1')
  listproduct pid rid hid vid
  goto('listproduct&pid=1&rid=1&hid=1&vid=1')
  listsupplier sid pid rid hid vid
  goto('listsupplier&pid=1&rid=1&hid=1&vid=1')
  */
	
    switch(dst.page) {
        case 'homepage':
                $('div#villagelistpeg ul li a').removeClass('selected');       
                if ($("#mainpeg").css("display") == 'none') {
                    //animation version
                    //$("#mainpeg").addClass("lower_container").fadeIn(FADE_SPEED);
                    //non-animation version
                    //$("#mainpeg").addClass("lower_container").show().fadeIn("normal");
                    $("#mainpeg").addClass("lower_container").show();
                }
                //update header (set to full)
                if (src.page == 'scrapbook' || src.page == 'search' || src.page == 'searchresults' || src.page == 'contactus') {
                  // new Ajax.Updater('flash', 'flashdetail.aspx', {method: 'get'});
                   //update top to load flash movie
                    //  with param to immediately load correct page in flash movie                
                } else {                
                    //set page in flash movie to homepage banner via js call to flash
                    
                }                                
                //update bottom half
                if (src.page == 'village' || src.page == 'house' || src.page == 'showcaseproduct' || src.page == 'listproduct' || src.page == 'listsupplier') { 
                	//can cheap out by only updating notvillagelist
                	//new Ajax.Updater('notvillagelist', 'controls.aspx?type=partial&ids=villagebasedarea,villagelist,homepagearea', {method: 'get'});
                	//postBackHiddenField(gotoDestination);
                } else {
                	//must show the whole panel
                	//new Ajax.Updater('htmlarea', 'controls.aspx?type=partial&ids=villagebasedarea,homepagearea', {method: 'get'});
                	//postBackHiddenField(gotoDestination);
                }
                $("#publicationlistpeg").empty().hide();
                $("#houselistpeg").empty().hide();
                $("#villagedetailpeg").empty().hide();
                $("#advertpeg").empty().hide();
                $("#showcasesupplierpeg").empty().hide();
                $("#housedetailpeg").empty().hide();
                $("#staticpeg").empty().hide();      
                $("#devloperdetailcontrol").empty().hide();
                if (requireContent('villagelistpeg',src,dst)) {
                    $("#villagelistpeg").html(villageListLoadingMessage());
                    $("#villagelistpeg").load("ajaxfragments/villagelist.aspx?"+gotoDestination,ajaxErrorHandler,hideHomeLink).show().fadeIn("normal");
                }
                if (requireContent('publicationdetailpeg',src,dst)) {
                //just stopping reload - unexciting, probably could remove
                    $("#publicationdetailpeg").html(publicationDetailLoadingMessage());
                    $("#publicationdetailpeg").load("ajaxfragments/publicationdetail.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
                }
                if (requireContent('homepagepeg',src,dst)) {
                    $("#homepagepeg").html(homepageDetailLoadingMessage());
                    $("#homepagepeg").load("ajaxfragments/homepage.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
                }
                /*
                if (!isFlashReady) {
                    debug("flash not ready");
                    document.title = '--- ' + "ajaxfragments/flash.aspx?"+gotoDestination;
                    $("#flashpeg").html(flashLoadingMessage());
                    $("#flashpeg").load("ajaxfragments/flash.aspx?"+gotoDestination + "&time="+new Date(),ajaxErrorHandler).show().fadeIn("normal");
                } else {
                    $("#flashpeg").show();
                }
                */
                if (!needToLoadFlash("ajaxfragments/flash.aspx?"+gotoDestination + "&time="+new Date())) {                
                    flashGoto("homepage",src.page,dst);                
                }
                /*
                basicUpdate('htmlarea',--no current way to get all three into this one area via partial.aspx--);
                or
                basicUpdate('htmlarea',--no current way to get all three into this one area via partial.aspx--);
                * ok so this actually would be in favour of a conditional display version of the full page. in fact, a conditional display mode in the
                single full page. where the only panels shown are the ones with the ids listed in the request. 
                now using controls.ascx ... hopefully
                */
            break;
        case 'village':
            $("#mainpeg").addClass("lower_container");                
            if (src.page == 'homepage') {
                //update header (set to small)
                //update top
                //   set flash page to village banner with image to vid
                //set selection on village list
                //display village details
                //postBackHiddenField(gotoDestination);
                
            } else if (src.page == 'village') {
                //set flash page to village with image to vid
                //set selection on village list
                //display village details
                //postBackHiddenField(gotoDestination);
                //$("#villagelist").load("VillageList.aspx");
            } else if (src.page == 'house' || src.page == 'room' || src.page == 'showcaseproduct' || src.page == 'listproduct' || src.page == 'listsupplier') {
                //set flash page to village with image to vid
                //set selection on village list
                //display village details
                //postBackHiddenField(gotoDestination);
               // $("#villagelist").load("VillageList.aspx");
            }
            $("#homepagepeg").empty().hide();
            $("#publicationdetailpeg").empty().hide();
            $("#publicationlistpeg").empty().hide();
            $("#showcasesupplierpeg").empty().hide();
            $("#housedetailpeg").empty().hide();
            $("#devloperdetailcontrol").empty().hide();
            $("#staticpeg").empty().hide();
            if ($("#mainpeg").css("display") == 'none') {
                $("#mainpeg").addClass("lower_container").show();
            }   
            /*             
            if (!isFlashReady) {
                //document.title = '--- ' + "ajaxfragments/flash.aspx?"+gotoDestination;
                $("#flashpeg").html(flashLoadingMessage());
                $("#flashpeg").load("ajaxfragments/flash.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            } else {
                $("#flashpeg").show();
            }
            */
            if (!needToLoadFlash("ajaxfragments/flash.aspx?"+gotoDestination + "&time="+new Date())) {            
				if(dst.flash == 'estate') {
					flashGoto("estate",src.page,dst);   
                } else {
				  flashGoto("village",src.page,dst);   
                }
            }
            if (requireContent('villagelistpeg',src,dst)) {
                $("#villagelistpeg").html(villageListLoadingMessage());
                $("#villagelistpeg").load("ajaxfragments/villagelist.aspx?"+gotoDestination,ajaxErrorHandler,hideHomeLink).show().fadeIn("normal");
            }
            if (requireContent('houselistpeg',src,dst)) {
                $("#houselistpeg").html(houseListLoadingMessage());
                $("#houselistpeg").load("ajaxfragments/houselist.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            }
            if (requireContent('villagedetailpeg',src,dst)) {
                //just stopping reload - unexciting, probably could remove
                $("#villagedetailpeg").html(villageDetailLoadingMessage());
                $("#villagedetailpeg").load("ajaxfragments/villagedetail.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            }
            if (requireContent('advertpeg',src,dst)) {
                //todo: finalise advert logic .. per village or what?
                $("#advertpeg").html(advertLoadingMessage());
                $("#advertpeg").load("ajaxfragments/advert.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            }
            //alert('dest ' + gotoDestination);
            //postBackHiddenField(gotoDestination);
            
            break;
        case 'developer':
			$("#publicationdetailpeg").empty().hide();
            $("#publicationlistpeg").empty().hide();
            $("#showcasesupplierpeg").empty().hide();
            $("#housedetailpeg").empty().hide();
			$("#houselistpeg").empty().hide();
			$("#villagedetailpeg").empty().hide();
            $("#homepagepeg").empty().hide();
            $("#publicationdetailpeg").empty().hide();
            $("#showcasesupplierpeg").empty().hide();
            $("#devloperdetailcontrol").empty().hide();
            $("#staticpeg").empty().hide(); 
            if ($("#mainpeg").css("display") == 'none') {
                $("#mainpeg").addClass("lower_container").show();
            }   
            if (!needToLoadFlash("ajaxfragments/flash.aspx?"+gotoDestination + "&time="+new Date())) {            
                if(dst.flash == 'estate') {
				  flashGoto("estate",src.page,dst);   
                } else {
				  flashGoto("developer",src.page,dst);   
                }
            }
            
            if (requireContent('advertpeg',src,dst)) {
                $("#advertpeg").html(advertLoadingMessage());
                $("#advertpeg").load("ajaxfragments/advert.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
                
            }
            if (requireContent('devloperdetailcontrol',src,dst)) {            
                $("#devloperdetailcontrol").html(developerLoadingMessage());
                $("#devloperdetailcontrol").load("ajaxfragments/developer.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            }	         		
            if (requireContent('villagelistpeg',src,dst)) {
                $("#villagelistpeg").html(villageListLoadingMessage());              
                $("#villagelistpeg").load("ajaxfragments/villagelist.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            }
			break;
        case 'house':        
        case 'houseproduct':
        case 'housesupplier':
        case 'room':
            
            if (src.page == 'village' || src.page == 'house' || src.page == 'room' || src.page == 'showcaseproduct' || src.page == 'listproduct' || src.page == 'listsupplier' || src.page == 'scrapbook') {
                //update top
                //update bottom
            }
            $("#villagedetailpeg").empty().hide();
            $("#homepagepeg").empty().hide();
            $("#publicationdetailpeg").empty().hide();
            $("#showcasesupplierpeg").empty().hide();
            $("#staticpeg").empty().hide(); 
            $("#devloperdetailcontrol").empty().hide();
            if ($("#mainpeg").css("display") == 'none') {
                $("#mainpeg").addClass("lower_container").show();
            }
            /*
            if (!isFlashReady) {
                //document.title = '--- ' + "ajaxfragments/flash.aspx?"+gotoDestination;
                $("#flashpeg").html(flashLoadingMessage());
                $("#flashpeg").load("ajaxfragments/flash.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            } else {
                $("#flashpeg").show();
            }
            */
            if (!needToLoadFlash("ajaxfragments/flash.aspx?"+gotoDestination + "&time="+new Date())) {
                flashGoto(dst.page,src.page,dst);            
            }
            
            if (requireContent('villagelistpeg',src,dst)) {
                //alert('req villagelist');
                $("#villagelistpeg").html(villageListLoadingMessage());
                $("#villagelistpeg").load("ajaxfragments/villagelist.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            }
            //,{},showHomeLink
            if (requireContent('houselistpeg',src,dst)) {            
                $("#houselistpeg").html(houseListLoadingMessage());
                $("#houselistpeg").load("ajaxfragments/houselist.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            }
            if (requireContent('advertpeg',src,dst)) {
                $("#advertpeg").html(advertLoadingMessage());
                $("#advertpeg").load("ajaxfragments/advert.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            }
            if (requireContent('housedetailpeg',src,dst)) {
                $("#housedetailpeg").html(houseDetailLoadingMessage());
                $("#housedetailpeg").load("ajaxfragments/housedetail.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            }
            
            //alert('dest ' + gotoDestination);
//            postBackHiddenField(gotoDestination);
            break;        
        case 'showcasesupplier':
            /*
            if (!isFlashReady) {
                //document.title = '--- ' + "ajaxfragments/flash.aspx?"+gotoDestination;
                $("#flashpeg").html(flashLoadingMessage());
                $("#flashpeg").load("ajaxfragments/flash.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            } else {
                $("#flashpeg").show();
            }
            */
            if (!needToLoadFlash("ajaxfragments/flash.aspx?"+gotoDestination + "&time="+new Date())) {
                flashGoto("showcasesupplier",src.page,dst);
            }
            $("#villagelistpeg").empty().hide();
            $("#houselistpeg").empty().hide();
            $("#housedetailpeg").empty().hide();
            $("#villagedetailpeg").empty().hide();
            $("#homepagepeg").empty().hide();
            $("#publicationdetailpeg").empty().hide();
            $("#showcasesupplierpeg").empty().hide();
            $("#staticpeg").empty().hide(); 
            $("#devloperdetailcontrol").empty().hide();
            if ($("#mainpeg").css("display") == 'none') {
                $("#mainpeg").addClass("lower_container").show();
            }
            
            if (requireContent('showcasesupplierpeg',src,dst)) {
                $("#showcasesupplierpeg").html(showcaseSupplierLoadingMessage());
                //document.location = "ajaxfragments/showcasesupplierdetail.aspx?"+gotoDestination
                $("#showcasesupplierpeg").load("ajaxfragments/showcasesupplierdetail.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            }
            if (requireContent('advertpeg',src,dst)) {
                //todo: finalise advert logic .. per village or what?
                $("#advertpeg").html(advertLoadingMessage());
                $("#advertpeg").load("ajaxfragments/advert.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            }
            
            break;
        case 'scrapbook':
            $("#mainpeg").removeClass("lower_container");
            if (src.page == 'homepage') {
                //update header (set to small)
            }
            //replace top and bottom with scrapbook panel
            break;
        case 'static':
            //if src = homepage and using large header, update header (set to small)                
             if (dst.type == 'logout') {
                $("#headerpeg").html(headerLoadingMessage());
                //$("#headerpeg").load("ajaxfragments/header.aspx",ajaxErrorHandler).show().fadeIn("normal");
                $("#headerpeg").loadIfModified("ajaxfragments/header.aspx",ajaxErrorHandler);
            }                
                
            if (src.page == 'static') {
                //alert("ajaxfragments/" + dst.type + ".aspx?"+gotoDestination);
                //$("#staticpeg").fadeOut(FADE_SPEED), function () { $("#staticpeg").load(dst.type + ".aspx").fadeIn(FADE_SPEED); }
                //$("#flashpeg").empty().hide();
                //isFlashReady = false;
                //$("#flashpeg").hide();
                hideFlash();
                
                $("#mainpeg").hide();
               $("#staticpeg").html(staticLoadingMessage());
                $("#staticpeg").load("ajaxfragments/" + dst.type + ".aspx?"+gotoDestination,ajaxErrorHandler);
                
            } else {
                //non-animation version
                //alert("ajaxfragments/" + dst.type + ".aspx?"+gotoDestination);
                $("#mainpeg").hide();
                //$("#flashpeg").empty().hide();                
                //isFlashReady = false;                
                //$("#flashpeg").hide();                
                hideFlash();
                
                $("#staticpeg").html(staticLoadingMessage());
                $("#staticpeg").load("ajaxfragments/" + dst.type + ".aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
                //animation version             
                /*
                $("#flashpeg").fadeOut(FADE_SPEED);
                $("#mainpeg").fadeOut(FADE_SPEED, function() { 
                    $("#staticpeg").hide().load(dst.type + ".aspx",function() {
                        $("#staticpeg").fadeIn(FADE_SPEED, function() {
                            $("#mainpeg").removeClass("lower_container");
                            $("#villagelistpeg").empty().hide();
                            //$("#flashpeg").empty().hide();
                            $("#homepagepeg").empty().hide();
                            $("#publicationpeg").empty().hide();
                            $("#houselistpeg").empty().hide();
                            $("#villagedetailpeg").empty().hide();
                            $("#advertpeg").empty().hide();
                            $("#showcasesupplierpeg").empty().hide();
                            $("#housedetailpeg").empty().hide();
                        });
                                            
                    });
                });
                */
            }            
            break;
        case 'search':
            //$("#flashpeg").empty().hide();
            //isFlashReady = false;
            //$("#flashpeg").hide();
            hideFlash();
            $("#mainpeg").hide();
            $("#staticpeg").html(staticLoadingMessage());
            $("#staticpeg").load("ajaxfragments/searchaction.aspx?"+gotoDestination,ajaxErrorHandler).show().fadeIn("normal");
            break;
        /* was...
        case 'search':
            $("#mainpeg").addClass("lower_container");
            if (src.page == 'homepage') {
                //update header (set to small)
            }
            //replace top and bottom with search results panel
            break;
        */
        case 'tweentest1':
            //set page in flash movie
            flashGoto("tweentest1",src.page,dst);
            break;
        case 'tweentest2':
            //set page in flash movie
            flashGoto("tweentest2",src.page,dst);
            break;
        }
  
  
}

function hideHomeLink() {
    $("#village_homelink").hide();
}

function register() {
	var options = {
	    url: "/ajaxfragments/registeraction.aspx",
        dataType: "json",
        type: "POST",
        success: function(data) {
           // 'data' is an object representing the the evaluated json data
            if (data.result=='true') {
                //$('#RegisterStatus').empty().append('<p>Registration successful.</p>');                
                $('#SuccessPanel').removeClass("screen_hide");
                $('#RegisterPanel').addClass("screen_hide");
            } else {
                $('#RegisterStatus').empty().append('<p>There was a problem registering: ' + data.description + '</p>');
            }
        }
    };
	$('#RegisterForm').ajaxSubmit(options);
	$('#RegisterStatus').empty().append('<p>Status: Communicating with server... <img src="/images/loading.gif"></p>');
	
	return false;
}


function forgot() {
	var options = {
	    url: "/ajaxfragments/forgotaction.aspx",
        dataType: "json",
        type: "POST",
        success: function(data) {	
           // 'data' is an object representing the the evaluated json data
            if (data.result=='true') {
                //$('#RegisterStatus').empty().append('<p>Registration successful.</p>');                
                $('#SuccessPanel').removeClass("display_none");
                $('#ForgotPanel').addClass("display_none");
            } else {
                $('#ForgotStatus').empty().append('<p>There was a problem registering: ' + data.description + '</p>');
            }
        }
    };
	$('#ForgotForm').ajaxSubmit(options);
	$('#ForgotStatus').empty().append('<p>Status: Communicating with server... <img src="/images/loading.gif"></p>');
	
	return false;
}
function login() {
	var options = {
	    url: "/ajaxfragments/loginaction.aspx",
        dataType: "json",
        type: "POST",
        success: function(data) {
           // 'data' is an object representing the the evaluated json data
            if (data.result=='true') {
                //$('#RegisterStatus').empty().append('<p>Registration successful.</p>');                
                
                $('#SuccessPanel').removeClass("display_none");
                $('#LoginPanel').addClass("display_none");
                
                //$('#login_options').addClass("screen_hide");
                //$('#logout_options').removeClass("screen_hide");
                $("#headerpeg").html(headerLoadingMessage());
                $("#headerpeg").loadIfModified("ajaxfragments/header.aspx",ajaxErrorHandler).show().fadeIn("normal");
            } else {
                $('#LoginStatus').addClass("error");
                $('#LoginStatus').empty().append('<p>There was a problem logging in: ' + data.description + '</p>');
            }
        }
    };
	$('#LoginForm').ajaxSubmit(options);
	$('#LoginStatus').removeClass("error");
	$('#LoginStatus').empty().append('<p>Status: Communicating with server... <img src="/images/loading.gif"></p>');
	
	return false;
}

function logout() {
    $.getJSON("/ajaxfragments/logoutaction.aspx",
    function(data) {
       // 'data' is an object representing the the evaluated json data
        if (data.result=='true') {
            //$('#LogoutStatus').empty().append('<p>Logout successful.</p>');                            
            setStateNow("page=static&type=logout");
            //$("#headerpeg").html(headerLoadingMessage());
            //$("#headerpeg").empty();
            //$("#headerpeg").load("ajaxfragments/header.aspx",ajaxErrorHandler).show().fadeIn("normal");            
            //GoTo("page=static&type=logout","");
        } else {
            alert('Problem logging out: ' + data.description);
        }
    });
 	$('#LogoutStatus').empty().append('<p>Status: Communicating with server... <img src="/images/loading.gif"></p>');
		
}

function contactUs() {
	$.post("ajaxfragments/contactusaction.aspx" ,  { email: document.ContactForm.email.value, name: document.ContactForm.name.value, message: document.ContactForm.message.value } ,
	function(data,status){
	   // alert("Data Loaded: " + data + "," + status);
	  }
	
	);
	setStateNow('page=static&type=contactedus');
	return false;
}

function addToScrapbook() {
	var hash = document.location.hash;
	hash = hash.replace(/#/g,'')
    var dst = queryParamsToObj(hash);    
    if (dst.page == 'houseproduct' || dst.page == 'housesupplier') {
        hash = "page=house&v=" + dst.v + "&h=" + dst.h;
        var dst = queryParamsToObj(hash);
    }
    dst.cmd = "add";
    $.ajax({
	    type:"POST",
	    url:"ajaxfragments/scrapbookaction.aspx",
	    data: dst,
	    error: function(request, err, obj) {
	        alert('There was an error communicating with the server: ' + err);
	    },
	    success: function(data){
	        try {
	            data = eval('(' +data+ ')');
	            if (data.result=='true') {
                    alert('Added item successfully to scrapbook.');
                } else {
                    if (data.description == 'Not logged in') {
                        alert("Please login to use the scrapbook feature");
                    } else {
                        alert('Unable to add item to scrapbook. Items can only be added once.');
                    }
                }        
            } catch (err) {
                alert("Unable to decipher result from server: " + data);
            }
	  }	
	});
	return false;
}


function saveNotes(noteId) {
    var dst = new Object();
    dst.cmd = "savenote";
    dst.note = document.ScrapbookForm.comment.value;
    dst.id = noteId;
    $.ajax({
	    type:"POST",
	    url:"ajaxfragments/scrapbookaction.aspx",
	    data: dst,
	    error: function(request, err, obj) {
	        alert('There was an error communicating with the server: ' + err);
	    },
	    success: function(data){
	        try {
	            data = eval('(' +data+ ')');
	            if (data.result=='true') {
                    alert('Notes saved successfully to scrapbook.');
                } else {
                    if (data.description == 'Not logged in') {
                        alert("Please login to use the scrapbook feature");
                    } else {
                        alert('Unable to save notes to scrapbook. ' + data.description);                    
                    }
                }        
            } catch (err) {
                alert("Unable to decipher result from server: " + data);
            }
	  }	
	});
	//return false;
}
function deleteScrapbookItem(noteId) {
    if (confirm('Are you sure you want to delete this scrapbook item?')) {
        reallyDeleteScrapbookItem(noteId);
    }
}

function reallyDeleteScrapbookItem(noteId) {
    var dst = new Object();
    dst.cmd = "delete";
    dst.id = noteId;
    $.ajax({
	    type:"POST",
	    url:"ajaxfragments/scrapbookaction.aspx",
	    data: dst,
	    error: function(request, err, obj) {
	        alert('There was an error communicating with the server: ' + err);
	    },
	    success: function(data){
	        try {
	            data = eval('(' +data+ ')');
	            if (data.result=='true') {
                    alert('Item deleted from scrapbook.');
                    setStateNow("page=static&type=scrapbook");
                } else {
                   if (data.description == 'Not logged in') {
                        alert("Please login to use the scrapbook feature");
                    } else {
                        alert('Unable to delete item from scrapbook. ' + data.description);                    
                    }
                }        
            } catch (err) {
                alert("Unable to decipher result from server: " + data);
            }
	  }	
	});
	//return false;
}

function ajaxErrorHandler(responseText,status,response) {
    if (status=='error') {
        //an error was received while communicating with the server
        
        //code for production system
        //(optional)alert("error in ajax call " + responseText + "," + status + "," + response);
        //setStateNow("page=static&type=error");
        var blank = window.open("/ajaxfragments/blank.html");
        blank.document.write("error in ajax call " + responseText + "," + status + "," + response);
        //alert("error in ajax call " + responseText + "," + status + "," + response);        
    }
}

function fixFlashErrorHandler(responseText,status,response) {
    if (status=='error') {
        alert(responseText);
        //alert("an error was received while communicating with the server.");
        setStateNow("page=static&type=error");
    } else {
        fixFlashTimeout = setTimeout("fixFlashIE()",200);
        /*theObjects = document.getElementsByTagName("object");
        for (var i = 0; i < theObjects.length; i++) {
            theObjects[i].outerHTML = theObjects[i].outerHTML;        
        } */       
    }

}

function fixFlashIE() {
    theObjects = document.getElementsByTagName("object");
    for (var i = 0; i < theObjects.length; i++) {
        theObjects[i].outerHTML = theObjects[i].outerHTML;        
    }
    clearTimeout(fixFlashTimeout);
}

function flashLoadingMessage() {
    return '<div id="flash"><div class="flash loading"></div></div>';
}
   
function staticLoadingMessage() {
    return '<div id="main"><div class="lower_static loading"></div></div>';
}

function villageListLoadingMessage() {
    return '<div id="villagelist"><h3>Display Villages</h3><div class="lower_villagelistLoading loading"></div></div>';
}

function publicationDetailLoadingMessage() {
    return '<div id="publication"><div class="lower_publications loading"></div></div>';
}
function homepageDetailLoadingMessage() {
    return '<div id="homepage"><div class="lower_blurb loading"></div></div>';
}
function houseListLoadingMessage() {    
    return '<div id="houselist"><h4>Choose a Home</h4><div class="homes_list"><div class="homes_list_table loading"></div></div></div>';
}
function developerLoadingMessage() {    
    return '<div id="houselist"><h4 class="loadingInfo">Loading Data...</h4><div class="homes_list"><div class="homes_list_table loading"></div></div></div>';
}
function houseDetailLoadingMessage() {    
    return '<div id="housedetail"><div class="lower_room_container loading"></div></div>';
}
function villageDetailLoadingMessage() {    
    return '<div id="villagedetail"><div class="lower_villagedetail loading"></div><div class="lower_maphours loading"></div></div>';
}
function advertLoadingMessage() {
    return '<div id="advert"><div class="lower_advert loading"></div></div>';
}
function headerLoadingMessage() {
    return '<div id="logos" class="loading"></div><div id="header_courtesy_nav" class="loading"></div>';
}
function showcaseSupplierLoadingMessage () {
    return '<div id="showcasesupplier" class="showcasesupplier loading"></div>'
}


function requireContent(pegName,src,dst) {
    if (src.page == 'firstview') {
        //on first view (also true for refresh in safari & ie) always require content
 
        return true;
    }
    var likelyReload = true;
    for (var i in src) {
        if (src[i] != dst[i]) {
            likelyReload = false;
        }
    }
    if ((likelyReload && isPossibleRefresh)) {
        //on refresh in firefox always require content
       
        return true;
    }
  
    //otherwise determine whether it needs to be loaded based on current and previous page parameters
    switch(pegName) { 
        case "advertpeg":
            var reqByPage = { //define which pages display the content for this peg
            "homepage":false,
            "developer":true,
            "village":true,
            "house":true,
            "houseproduct":true,
            "housesupplier":true,
            "room":true,
            "showcasesupplier":true,
            "search":false,
            "static":false}
    
            if (reqByPage[dst.page]) {
                return true;
            } else {
                return false;
            }

        break;   
             
        case "flashpeg":
            var reqByPage = { //define which pages display the content for this peg
            "homepage":true,
            "village":true,
            "house":true,
            "houseproduct":true,
            "housesupplier":true,
            "room":true,
            "showcasesupplier":true,
            "devloper":false,
            "search":false,
            "static":false}
            
            if (reqByPage[dst.page] && !reqByPage[src.page]) {
                return true;
            } else {
                return false;
            }
        break;
        
        case "homepagepeg":
            var reqByPage = { //define which pages display the content for this peg
            "homepage":true,
            "village":false,
            "house":false,
            "houseproduct":false,
            "housesupplier":false,
            "room":false,
            "showcasesupplier":false,
            "devloperdetailcontrol":false,
            "search":false,
            "static":false}
            
            if (reqByPage[dst.page] && !reqByPage[src.page]) {
                return true;
            } else {
                return false;
            }
        break;
        
        
        case "housedetailpeg":
            var reqByPage = { //define which pages display the content for this peg
            "homepage":false,
            "village":false,
            "house":true,
            "houseproduct":true,
            "housesupplier":true,
            "room":true,
            "showcasesupplier":false,
            "devloper":false,
            "search":false,
            "static":false}
            
            if (reqByPage[dst.page] && !reqByPage[src.page]) {
                return true;
            } else if (reqByPage[dst.page] && reqByPage[src.page] && dst.h != src.h) {
                return true;
            } else {
                return false;
            }
        break;
        case "villagedetailpeg":
            var reqByPage = { //define which pages display the content for this peg
            "homepage":false,
            "village":true,
            "house":false,
            "houseproduct":false,
            "housesupplier":false,
            "room":false,
            "showcasesupplier":false,
            "devloper":true,
            "search":false,
            "static":false}
            
            if (reqByPage[dst.page] && !reqByPage[src.page]) {
                return true;
            } else if (reqByPage[dst.page] && reqByPage[src.page] && dst.v != src.v) {
                return true;
            } else {
                return false;
            }
        break;
        
        case "villagelistpeg":
            
            var reqByPage = { //define which pages display the content for this peg
            "homepage":true,
            "village":true,
            "house":true,
            "houseproduct":true,
            "housesupplier":true,
            "room":true,
            "showcasesupplier":false,
            "developer":true,
            "search":false,
            "static":false}
     
            if (reqByPage[dst.page] && !reqByPage[src.page]) {
				
                return true;                       
            } else if (reqByPage[dst.page] && reqByPage[src.page] && dst.page == 'homepage') {
                $('#village_homelink').hide();
                $('#lower_villagelist').addClass('lower_villagelist');
                $('#lower_villagelist').removeClass('lower_villagelistHome');     
				
                return false;           
            } else if (reqByPage[dst.page] && reqByPage[src.page] && dst.page != 'homepage') {
                $('#village_homelink').show().fadeIn("normal");
                $('#lower_villagelist').addClass('lower_villagelistHome');
                $('#lower_villagelist').removeClass('lower_villagelist');  
                              
                return false;
            } else if (reqByPage[dst.page] && (dst.page == 'village'||dst.page=='developer')) {
                //reload here to get highlight
                
                return true;
            } else {     
				
               return false;
            }
        break;
        
        case "houselistpeg":
        //probably not required as only shown on a single page
            var reqByPage = { //define which pages display the content for this peg
            "homepage":false,
            "village":true,
            "house":true,
            "houseproduct":true,
            "housesupplier":true,
            "room":true,
            "devloper":false,
            "showcasesupplier":false,
            "search":false,
            "static":false}
            
            if (reqByPage[dst.page] && !reqByPage[src.page]) {
                return true;
            //} else if (reqByPage[dst.page] && reqByPage[src.page] && dst.v == src.v) {                
            //    return false; 
            //} else if (reqByPage[dst.page] && dst.page == 'house') {
                //reload here to get highlight
            //    return true;
            } else if (reqByPage[dst.page] && dst.v != src.v) {
                return true;
            } else {
                return false;
            }
        break;
        
        case "publicationdetailpeg":
        //probably not required as only shown on a single page
            var reqByPage = { //define which pages display the content for this peg
            "homepage":true,
            "village":false,
            "house":false,
            "houseproduct":false,
            "housesupplier":false,
            "room":false,
            "devloper":false,
            "showcasesupplier":false,
            "search":false,
            "static":false}
            
            if (reqByPage[dst.page] && !reqByPage[src.page]) {
                return true;
            } else {
                return false;
            }
        break;
        
        case "showcasesupplierpeg":
        //probably not required as only shown on a single page
            var reqByPage = { //define which pages display the content for this peg
            "homepage":false,
            "village":false,
            "house":false,
            "houseproduct":false,
            "housesupplier":false,
			"devloper":false,
            "room":false,
            "showcasesupplier":true,
            "search":false,
            "static":false}
            
            if (reqByPage[dst.page] && !reqByPage[src.page]) {
                return true;
            } else {
                return false;
            }
        break;
        
        case "staticpeg":
        //probably not required as only shown on a single page
            var reqByPage = { //define which pages display the content for this peg
            "homepage":false,
            "village":false,
            "house":false,
            "houseproduct":false,
            "housesupplier":false,
            "devloper":false,
            "room":false,
            "showcasesupplier":false,
            "search":true,
            "static":true}
            
            if (reqByPage[dst.page] && !reqByPage[src.page]) {
                return true;
            } else {
                return false;
            }
        break;  
         case "devloperdetailcontrol":
        //probably not required as only shown on a single page
            var reqByPage = { //define which pages display the content for this peg
            "advertpeg":true,
            "homepage":true,
            "village":true,
            "house":true,
            "houseproduct":false,
            "housesupplier":false,
            "devloper":true,
            "room":false,
            "showcasesupplier":false,
            "search":true,
            "static":false}
            return true;
            if (reqByPage[dst.page] && !reqByPage[src.page]) {
                return true;
            } else {
                return false;
            }
        break;  
    default:		
        //we'll know theres an unhandled case if it starts popping up on every page!
        alert("not found");
        return true;
    }
}
 
function needToLoadFlash(url) {
    if (!isFlashReady) {
        debug("url:"+url);
        $("#flashpeg").html(flashLoadingMessage());
        $("#flashpeg").load(url,ajaxErrorHandler).show().fadeIn("normal");
        return true;
    } else {    
        $("#flashpeg").show();
        return false;
    }    
}    

function hideFlash() {
    $("#flashpeg").empty().hide();
    isFlashReady = false;
}   
/*function addToScrapbook(param) {
    alert('add to scrapbook');
}*/
function viewScrapbook(param) {
    setStateNow("page=static&type=scrapbook");
}
function aboutScrapbook(param) {
    setStateNow('page=static&type=aboutscrapbook');
}
function fullFlashDebug() {
    var blank = window.open("/ajaxfragments/blank.html");
    var flashResponse = thisMovie("Masterbuilders3").fullDebug();
    blank.document.write(flashResponse);
}
function requestFlashValue(str) {
    alert(thisMovie("Masterbuilders3").requestValue(str));
}

function saveScrapbookPDF() {
    
}

function printScrapbook() {
    $.ajax({
	    type:"GET",
	    url:"ajaxfragments/scrapbook.aspx?page=static&type=scrapbook&cmd=print",
	    error: function(request, err, obj) {
	        alert('There was an error communicating with the server: ' + err);
	    },
	    success: function(data){
	        try {
	            var blank = window.open("/ajaxfragments/blank.html");                
	            blank.document.write("<html>");
	            
	            blank.document.write('<head><link rel="stylesheet" type="text/css" href="/app_themes/public/common.css" /></head>');
	            blank.document.write("<body onload='print();'>");
                blank.document.write(data);
                blank.document.write("</body></html>");
                blank.document.close();
            } catch (err) {
                alert("Unable to decipher result from server: " + data);
            }
	  }	
	});    
}

/*
function doNewResize() {
	var paddingTop = parseInt(( (window.innerHeight ? window.innerHeight : document.body.offsetHeight) - 600) / 2);
	$('body').css('padding-top', paddingTop);
}

$(function(){
	doNewResize();
});
$(window).resize(function(){
	doNewResize();
});
*/