/**
 * hotels.com module handler pseudocode
 *
 **/

// receive full question response, and next Q image preload data

// populate first question

// set timeout on creating images in background (see YUI imageloader). Maybe even create full markup for next Q. Can be done via AJAX whilst user is answering question

// save answer responses client side

// once all answers have been completed, show demographics

// if demographics completed, submit response

var Youniverse = {};



//YAHOO.Youniverse.module = function()
Youniverse.module = function()
{
    /**
     * The internal module reference
     * @var string
     */
    var moduleId;
    
    
    /**
     * The other internal module reference
     * @var integer
     */
    var moduleUid;
    
    /**
     * The name of the module
     * @var string
     */
	var moduleName;    
    
    /**
     * If supplied, indicates that the resulting results should overwrite those for the supplied team
     * (i.e. we are in a "REDO" situation)
     */
    var teamId
    
    /**
     * The URL of finish.php
     * @var string
     */
    var finishPostUrl;
    
    /**
	 * Set to true when a click has been made, so extra clicks can't be made. Reset upon AJAX success
	 */
    var hasClicked;
    
    /**
     * Original JSON data containing statements
     */
    var sData;
    
    /**
     * Array containing the statements for this module
     * @var array
     */
    var statements;
    
    /**
     * Array containing choice image objects
     * @var array
     */
    var choiceImages;
    
    /**
     * The ID of the current statement being shown
     * @var int
     */
    var currentStatement;
    
    /**
     * Array containing the user's statement choices
     * @var array
     */
    var userChoices;
    
    /**
     * Array containing URLs of chosen images
     * @var array
     */    
    var clickStream;
    
    /**
     * Defines if a user has completed a module
     * @var boolean
     */
    var completedModule;
    
    /**
     * Load a module
     * 
     */
    this.loadModule = function (modUid, modId, modName, tmId, finPostUrl)
    {
        hasClicked      = false;
        moduleUid       = modUid;
        moduleId        = modId;
		moduleName      = modName;
        teamId = tmId;
        finishPostUrl   = finPostUrl;
        userChoices     = new Array;
        clickStream     = new Array;
        choiceImages    = new Array;        
        completedModule = false;        

        // create the URL
        var urlString = "/statement/module_process/" + moduleId;
        
		//new call
		var request = $.ajax({ 
			type: 'GET',
			url: urlString,
			dataType: 'json',
			success: this.onLoadModule,
			failure: this.ajaxFailure,
			cache: false
		
		});
    }
    
    /**
     * onLoadModule callback function
     * 
     * @param o
     */
    this.onLoadModule = function (o)
    {
		// responseText is JSON. Parse it to get the response object
        var responseObject = eval(o);
        
        // reset the has clicked flag
        clicked = false; 
        
        // check the current module status
        if (responseObject.status == 'statements')
		{
			floatingModule.createStatements(responseObject);
		}
		else if (responseObject.status == 'demographics')
		{          
			// Analytics
			pageTracker._trackPageview('/statement/module/' + moduleName + '/' + moduleId + '/demographics');
            
			floatingModule.createDemographics(responseObject);
		}
		else
		{
            // Analytics
			pageTracker._trackPageview('/statement/module/' + moduleName + '/' + moduleId + '/completed');
            
			floatingModule.createProcessingPage(responseObject.resultsPage);
		}
    }
    
    /**
	 * Create the statements for the current module
	 * 
	 */
	this.createStatements = function (responseObject)
	{
        // stick the statements into an array - it's easier to go from one t'other this way
        statements = new Array;
        
        sData = responseObject.statements;
        
        var statementCount = 0;
        for (statement in sData)
		{
            statements[statementCount] = sData[statement];
            statementCount++;
        }
        
        // begin preloading of first statement images
        this.preloadStatementImages(0);
        
        // create the basic statement markup
		var modulePanelBD = document.createElement('div');
		modulePanelBD.setAttribute('id', 'modulePanelBD');
		
		var inner = document.createElement('div');
		inner.setAttribute('id', 'inner');
		inner.className = 'inner';
		
        // display the first statement
        var statementTitle = this.fetchNextStatement(0);
        var markup         = this.createStatementMarkup();
        
        modulePanelBD.innerHTML = "<h2 class='module' id='statementTitle'>" + statementTitle + "</h2>";
        inner.appendChild(markup);
		modulePanelBD.appendChild(inner);
		
        modulePanelBD.innerHTML += '<div id="progressBar"><div id="progressDone"></div></div>';
		modulePanelBD.innerHTML += "<div id='optionButtons'><a id='redoButton' onclick='floatingModule.redoModule(); return false;' href='#' tip='" + responseObject.statementButtons.redo + "'><img src='/img/buttons/btn-redo.gif' alt='begin again' title='begin again' /></a></div>";

		this.displayModule(modulePanelBD);
	}
    
    /**
     * Begins preloading all images in a specific statement
     *
     * @param statementId - the numeric statementId (1 to numStatements)
     */
    this.preloadStatementImages = function (statementId)
    {
        var statement = statements[statementId];
        
        var choicesObj = statement.choices;
        
		for (choice in choicesObj)
		{
            choiceImages[choice] = new Image;
            choiceImages[choice] = choicesObj[choice].src;
		}
    }
    
    /**
     * Fetches the next statement, and triggers the preloading of the images for the statement after that
     *
     */
    this.fetchNextStatement = function (statementID)
    {
        if (statementID == undefined)
        {
            currentStatement++;
        }
        else
        {
            currentStatement = statementID;
        }
        
        if (currentStatement >= statements.length)
        {
            completedModule = true;
            return false;
        }
        
        if (currentStatement < statements.length - 1)
        {
            this.preloadStatementImages(currentStatement + 1);
        }
        
        return statements[currentStatement].statement_text;
    }
    
    /**
     * Creates the markup for the current statement
     * 
     */
    this.createStatementMarkup = function ()
    {
		var statement  = statements[currentStatement];
		var choicesObj = statement.choices;
        var markup     = '';
        
        var statementBlock = document.createElement('div');
		statementBlock.setAttribute('id', 'statementBlock');
        
		for (choice in choicesObj)
		{
            
                var link = document.createElement('a');
                
                link.setAttribute('href', 'javascript:floatingModule.saveStatement(\''+ choicesObj[choice].id +'\', \''+ statement.statement_id +'\', \'' + choicesObj[choice].src + '\');');
                link.setAttribute('id', 'choice-' + choicesObj[choice].id);
                
                //append click event
                
                var choiceImg = document.createElement('img');
                choiceImg.setAttribute('id', choicesObj[choice].id);
                //choiceImg.setAttribute('alt', choicesObj[choice].statementId);
                choiceImg.setAttribute('alt', '');
                choiceImg.setAttribute('src', choicesObj[choice].src);
                
                link.appendChild(choiceImg);
                
                statementBlock.appendChild(link);                
	        }
        
		// Analytics
		pageTracker._trackPageview('/statement/module/' + moduleName + '/' + moduleId + '/statement/' +  statement.statement_id);
        
        return statementBlock;
    }
    
    /**
     * Outputs the module markup
     *
     */
    this.displayModule = function (moduleContent)
    {
        var moduleContainer = document.getElementById('moduleContainer');
        
		// This is an IE-safe equivalent of doing innerHTML = '';
		while (moduleContainer.hasChildNodes()) moduleContainer.removeChild(moduleContainer.firstChild);
        
		moduleContainer.appendChild(moduleContent);
		
		var cap = document.createElement('div');
		cap.className = 'cap';
		
		moduleContainer.appendChild(cap);
    }
    
    /**
     * Creates the progress bar for a modul
     * 
     */
    this.displayProgressBar = function ()
    {
        var percentageDone = (currentStatement / statements.length);
        var width = (288 * percentageDone);
        document.getElementById('progressDone').style.width = width + 'px';
    }
    
    /**
	 * Save the statement response and display the next statement in the module
	 * 
	 * @param statementID
	 * @param choiceID
	 */
	this.saveStatement = function (choiceId, statementId, imageSrc)
	{
		// check if user has already clicked an image. Ignore the click if they have
		if (hasClicked == false)
		{
            var statementID = statementId;
            var choiceID    = choiceId;
            
            hasClicked = true;
            userChoices[statementID] = choiceID;
            clickStream.push(imageSrc);
            
            var statementTitle = floatingModule.fetchNextStatement();
            
            if (statementTitle == false)
            {
                // user has completed the module, save response and check demographics status
                this.saveResponses();
            }
            else
            {
                var markup = this.createStatementMarkup();
                document.getElementById('statementTitle').innerHTML = statementTitle;
                var inner = document.getElementById('inner');
                while (inner.hasChildNodes()) inner.removeChild(inner.firstChild);
                inner.appendChild(markup);
                this.displayProgressBar();
            }
            
			hasClicked = false;
		}
	}
    
    /**
     * Saves the responses and checks if the demographics page should be loaded
     *
     */
    this.saveResponses = function ()
    {
        
	   // create the URL
        var urlString = "/statement/save_response/" + moduleId;
        
        var postData = 't=1';
        // create the choices POST data
        for (statement in userChoices)
        {
            postData += '&data[Response][' + statement + ']=' + userChoices[statement];
        }        

		//new call
		var request = $.ajax({ 
			type: 'POST',
			url: urlString,
			data: postData,
			dataType: 'json',
			success: this.onSaveResponse,
			failure: this.ajaxFailure,
			cache: false
		
		});
    }
    
    /**
     * Callback function called when a user's responses are saved
     * 
     * @param o JSON response object
     */
    this.onSaveResponse = function (o)
    {
        // responseText is JSON. Parse it to get the response object
        var responseObject =  eval( o );
        
        //if (responseObject.showDemographics == true)
       // {
            floatingModule.createDemographics(responseObject);
        //}
       // else
        //{
        //    floatingModule.createProcessingPage(responseObject.resultsPage);
       // }
    }

	/**
	 * Create Demographics markup
	 * 
	 */
	this.createDemographics = function (responseObject)
	{
		
		var modulePanelBD = document.createElement('div');
		modulePanelBD.setAttribute('id', 'modulePanelBD');
		
		var col1 = document.createElement('div');
		col1.setAttribute('id', 'col1');
		modulePanelBD.appendChild(col1);
		
		col1.innerHTML = "<h1 titl='" + responseObject.demographicHeader + "'>" + responseObject.demographicHeader + "</h1>";
		
		var col2 = document.createElement('div');
		col2.setAttribute('id', 'col2');
		col2.className = "demog";
		modulePanelBD.appendChild(col2);
		
		var profileContentForm = document.createElement('form');
		profileContentForm.setAttribute('id', 'profileContentForm');
		profileContentForm.setAttribute('name', 'profileContentForm');
		profileContentForm.setAttribute('method', 'post');        
		//profileContentForm.onsubmit = 'hotelsdotcom.validateDemographicsForm(); return false;'; 
		profileContentForm.setAttribute('action', finishPostUrl);
		
		var demographics = responseObject.demographics;
		
		//demographics wrapper
		var demographicsWrapper = document.createElement('div');
		demographicsWrapper.setAttribute('id','demgraphicsWrapper');

		//hidden uid
		//var elModuleUid = document.createElement('input');
		//elModuleUid.setAttribute('type','hidden');
        //elModuleUid.setAttribute('name','module_uid');
		//elModuleUid.name ='module_uid';
		//elModuleUid.setAttribute('id','module_uid');
		//elModuleUid.setAttribute('value',moduleUid);

		if (navigator.appName == "Microsoft Internet Explorer") {
		var elModuleUid = demographicsWrapper.appendChild(document.createElement("<input type=\"hidden\" name=\"module_uid\" value=\"" + moduleUid + "\" />"));
		} else {
			var elModuleUid = demographicsWrapper.appendChild(document.createElement("input"));
			elModuleUid.setAttribute("type", "hidden");
			elModuleUid.setAttribute("name", "module_uid");
			elModuleUid.setAttribute('value', moduleUid);
		}

		//demographicsWrapper.appendChild(elModuleUid);

		//hidden exit url
		//var exitUrl = document.createElement('input');
		//exitUrl.setAttribute('type','text');
		//exitUrl.setAttribute('name','exitURL');
		//exitUrl.setAttribute('value','http://' + window.location.hostname + '/statement/finalize'+(teamId ? '/'+teamId : ''));
		//console.log(window.location.hostname);
		//demographicsWrapper.appendChild(exitUrl);

		if (navigator.appName == "Microsoft Internet Explorer") {
		var elExitUrl = demographicsWrapper.appendChild(document.createElement("<input type='hidden' name='exitURL' value='http://"+ window.location.hostname + "/statement/finalize"+ (teamId ? "/" + teamId : "" ) +"' />"));
		} else {
			var elExitUrl = demographicsWrapper.appendChild(document.createElement("input"));
			elExitUrl.setAttribute("type", "hidden");
			elExitUrl.setAttribute("name", "exitURL");
			elExitUrl.setAttribute('value', 'http://' + window.location.hostname + '/statement/finalize'+(teamId ? '/'+teamId : ''));
			//console.log(window.location.hostname);
		}
		
		//demographics ordered list
		var orderedList = document.createElement('ol');

		var listElement1  = document.createElement('li');
		listElement1.setAttribute('id','listElement1');
		
		var listElementDivInner = document.createElement('div');
		listElementDivInner.className = 'inner';
		listElementDivInner.innerHTML = '<h2 title="'+ demographics.gender.header +'">'+ demographics.gender.header +'</h2>';
		
		var listElementDivAnswers = document.createElement('div');
		listElementDivAnswers.className = 'answers';
		
		var listElementDivAnswerCol = document.createElement('div');
		listElementDivAnswerCol.className = 'answer-col';
		
		var stylefix = "";
		if(/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) stylefix = ' style="top: 2px; left: 2px;" ';
		if(window.devicePixelRatio) stylefix = ' style="left: 3px;" ';
		
		listElementDivAnswerCol.innerHTML += '<label for="male" id="labelMale"><img src="/img/module/demo-male.png" alt="Male" /></label><div class="radio" id="radioMale"><input type="radio" name="demog-gender" id="male" value="m"'+stylefix+'/></div>';
		
		listElementDivAnswers.appendChild(listElementDivAnswerCol);
		
		var listElementDivAnswerCol = document.createElement('div');
		listElementDivAnswerCol.className = 'answer-col';
		listElementDivAnswerCol.innerHTML += '<label for="female" id="labelFemale"><img src="/img/module/demo-female.png" alt="Female" /></label><div class="radio" id="radioFemale"><input type="radio" name="demog-gender" id="female" value="f"'+stylefix+'/></div>';

		listElementDivAnswers.appendChild(listElementDivAnswerCol);
		
		listElementDivInner.appendChild(listElementDivAnswers);
		listElement1.appendChild(listElementDivInner);
		orderedList.appendChild(listElement1);

		var listElement2  = document.createElement('li');
		listElement2.setAttribute('id','listElement2');
		
		var listElementDivInner = document.createElement('div');
		listElementDivInner.className = 'inner';
		listElementDivInner.innerHTML = '<h2 title="'+ demographics.trip.header +'">'+ demographics.trip.header +'</h2>';
		
		var listElementDivAnswers = document.createElement('div');
		listElementDivAnswers.className = 'answers';
		
		var listElementDivAnswerCol = document.createElement('div');
		listElementDivAnswerCol.className = 'answer-col';
		listElementDivAnswerCol.innerHTML += '<label for="leisure" id="labelLeisure"><img src="/img/module/demo-leisure.png" alt="Leisure" /></label><div class="radio" id="radioLeisure"><input type="radio" name="data-trip-type" id="leisure" value="leisure"'+stylefix+'/></div>';
		
		listElementDivAnswers.appendChild(listElementDivAnswerCol);
		
		var listElementDivAnswerCol = document.createElement('div');
		listElementDivAnswerCol.className = 'answer-col';
		listElementDivAnswerCol.innerHTML += '<label for="business" id="labelBusiness"><img src="/img/module/demo-business.png" alt="Business" /></label><div class="radio" id="radioBusiness"><input type="radio" name="data-trip-type" id="business" value="business"'+stylefix+'/></div>';
		
		listElementDivAnswers.appendChild(listElementDivAnswerCol);
		
		var listElementDivAnswerCol = document.createElement('div');
		listElementDivAnswerCol.className = 'answer-col';
		listElementDivAnswerCol.innerHTML += '<label for="both" id="labelBoth"><img src="/img/module/demo-both.png" alt="Both" /></label><div class="radio" id="radioBoth"><input type="radio" name="data-trip-type" id="both" value="both"'+stylefix+'/></div>';
		
		listElementDivAnswers.appendChild(listElementDivAnswerCol);
		
		listElementDivInner.appendChild(listElementDivAnswers);
		listElement2.appendChild(listElementDivInner);
		orderedList.appendChild(listElement2);

		var listElement3  = document.createElement('li');
		listElement3.setAttribute('id','listElement3');
		
		var listElementDivInner = document.createElement('div');
		listElementDivInner.className = 'inner';
		listElementDivInner.innerHTML = '<h2 title="'+ demographics.age.header +'">'+ demographics.age.header +'</h2>';
		
		var listElementDivAnswers = document.createElement('div');
		listElementDivAnswers.className = 'answers';
		
		var listElementDivAnswerCol = document.createElement('div');
		listElementDivAnswerCol.className = 'answer-col';
		listElementDivAnswerCol.innerHTML += '<label for="ageRangeUnder18" id="labelAge1"><img src="/img/module/demo-age.png" alt="Under 18\'s" /></label><div class="radio" id="radioAge1"><input type="radio" name="demog-ageRange" id="ageRangeUnder18" value="under18s"'+stylefix+'/></div>';
		
		listElementDivAnswers.appendChild(listElementDivAnswerCol);
		
		var listElementDivAnswerCol = document.createElement('div');
		listElementDivAnswerCol.className = 'answer-col';
		listElementDivAnswerCol.innerHTML += '<label for="ageRange18_30" id="labelAge2"><img src="/img/module/demo-age-1.png" alt="18-30" /></label><div class="radio" id="radioAge2"><input type="radio" name="demog-ageRange" id="ageRange18_30" value="18_30"'+stylefix+'/></div>';
		
		listElementDivAnswers.appendChild(listElementDivAnswerCol);
		
		var listElementDivAnswerCol = document.createElement('div');
		listElementDivAnswerCol.className = 'answer-col';
		listElementDivAnswerCol.innerHTML += '<label for="ageRange31_50" id="labelAge3"><img src="/img/module/demo-age-2.png" alt="51+" /></label><div class="radio" id="radioAge3"><input type="radio" name="demog-ageRange" id="ageRange31_50" value="31_50"'+stylefix+'/></div>';
		
		listElementDivAnswers.appendChild(listElementDivAnswerCol);

		var listElementDivAnswerCol = document.createElement('div');
		listElementDivAnswerCol.className = 'answer-col';
		listElementDivAnswerCol.innerHTML += '<label for="ageRange51plus" id="labelAge4"><img src="/img/module/demo-age-3.png" alt="51+" /></label><div class="radio" id="radioAge4"><input type="radio" name="demog-ageRange" id="ageRange51plus" value="51_"'+stylefix+'/></div>';
		
		listElementDivAnswers.appendChild(listElementDivAnswerCol);

		listElementDivInner.appendChild(listElementDivAnswers);
		listElement3.appendChild(listElementDivInner);
		orderedList.appendChild(listElement3);

		var listElement4  = document.createElement('li');
		listElement4.setAttribute('id','listElement4');
		
		var listElementDivInner = document.createElement('div');
		listElementDivInner.className = 'inner';
		listElementDivInner.innerHTML = '<h2 title="Do you know where you want to go?">Do you know where you want to go?</h2>';
		
		var listElement4DivDestination  = document.createElement('div');
		listElement4DivDestination.className = "destination";
		listElement4DivDestination.innerHTML += '<label for="destination">Destination</label>';
		
		if (navigator.appName == "Microsoft Internet Explorer") {
			var destinationSel = document.createElement('<select id="destination" name="data-filter-marketName">');
		}else{
			var destinationSel = document.createElement('SELECT');
			destinationSel.setAttribute('id', 'destination');
			destinationSel.setAttribute('name', 'data-filter-marketName');
		}
		
		var countries = demographics.destination.countries;
		//var count = 0;
		
		var inviteAction = document.createElement('option');
        inviteAction.value = '---';
        inviteAction.innerHTML = "Select "+demographics.destination.settingName+' Destination';
        
        destinationSel.appendChild(inviteAction);
		
		var inviteAction = document.createElement('option');
        inviteAction.value = '---';
        inviteAction.innerHTML = "----------------------------------";
        
        destinationSel.appendChild(inviteAction);
		
        var inviteAction = document.createElement('option');
        inviteAction.value = '';
        inviteAction.innerHTML = "I don't know - Just surprise me!";
        
        destinationSel.appendChild(inviteAction);
		
		var inviteAction = document.createElement('option');
        inviteAction.value = '---';
        inviteAction.innerHTML = "----------------------------------";
        
        destinationSel.appendChild(inviteAction);
        
        // Process the available destinations        
		for (var countryCode in countries) {
            var optGroup = document.createElement('optgroup');
            optGroup.value = '';
            optGroup.label = countries[countryCode]['countryName'];
            
            var choices = countries[countryCode]['choices'];
            for (var i = 0; i < choices.length; i++ ) {
                if(countryCode=='00' && i==choices.length-1){
					break;
				}
				var opt = document.createElement('option');
                opt.value = choices[i];
                opt.innerHTML = choices[i];
                optGroup.appendChild(opt);
            }
        
            destinationSel.appendChild(optGroup);
			
			if(countryCode=='00'){ // indicates the 'most popular' section
				var inviteAction = document.createElement('option');
				inviteAction.value = '---';
				inviteAction.innerHTML = "----------------------------------";
				
				destinationSel.appendChild(inviteAction);			
			}
			
        }        
        
		listElement4DivDestination.appendChild(destinationSel);
		
		listElementDivInner.appendChild(listElement4DivDestination);
		
		listElement4.appendChild(listElementDivInner);
		
		orderedList.appendChild(listElement4);

		var hiddenFields = document.createElement('div');
		hiddenFields.setAttribute('id', 'statementChoices');


		var responses = responseObject.moduleResponses;
		var inc = 0;
		
		for (var response in responses)
		{			
			if (navigator.appName == "Microsoft Internet Explorer") {
			var resp = demographicsWrapper.appendChild(document.createElement("<input type=\"hidden\" name=\"resp-"+ response +"\" value=\"" + responses[response] + "\" />"));
			} else {
				var resp = demographicsWrapper.appendChild(document.createElement("input"));
				resp.setAttribute("type", "hidden");
				resp.setAttribute("name", "resp-" + response);
				resp.setAttribute('value', responses[response]);
			}

			hiddenFields.appendChild(resp);
			
			inc ++;
		}
        
        // Clickstream
        
        for (var i=0; i <clickStream.length; i++)
        {
            if (navigator.appName == "Microsoft Internet Explorer") {
			var resp = demographicsWrapper.appendChild(document.createElement("<input type=\"hidden\" name=\"data-clickStream" + i + "\" value=\"" + clickStream[i] + "\" />"));
			} else {
				var resp = demographicsWrapper.appendChild(document.createElement("input"));
				resp.setAttribute("type", "hidden");
				resp.setAttribute("name", "data-clickStream"+i);
				resp.setAttribute('value', clickStream[i]);
			}

			hiddenFields.appendChild(resp);			
			
        }
		
		demographicsWrapper.appendChild(hiddenFields);
		
		demographicsWrapper.appendChild(orderedList);
		profileContentForm.appendChild(demographicsWrapper);

		profileContentForm.innerHTML += "<p id='bye'>" + responseObject.demographicFooter + "</p>";
		
		// needed!
		profileContentForm.innerHTML += "<p id='errorText'></p>";
		
		var formButtons= document.createElement('div');
		
		formButtons.className = 'formButtons';
		profileContentForm.appendChild(formButtons);
		var extraStyle = "";
        if (responseObject.demographicSubmitStyle)
        {
            extraStyle = responseObject.demographicSubmitStyle;
        }
		
        //formButtons.innerHTML += "<div id='submitDemogButton' class='imageLabel'><input type='image' class='submit' src='/img/buttons/btn-demo-find.gif' alt='find hotels' title='find hotels' /></div>";
		formButtons.innerHTML += "<div id='submitDemogButton' class='imageLabel'><div id='terms'><p>By clicking <em>find hotels</em> you are indicating that you have read, understood and agreed to the <a href='/termsandconditions/' title='View Terms and conditions (opens in a new window)' target='_blank'>Terms &amp; conditions</a> and <a href='/privacypolicy/' title='View Privacy Policy (opens in a new window)' target='_blank'>Privacy Policy</a> for this site, a copy of which can be found here.</p></div><img src='/img/buttons/btn-demo-find.gif' alt='submit' title='find hotels' /></div>";
        //formButtons.innerHTML += "<div id='cancelButton' class='imageLabel'><a  href='#' class='image' style='float: left;' title='" +responseObject.demographicCancel + "' onclick='floatingModule.cancelButton(); return false;'/></a><div class='caption' style='float: left; display: table;'><a class='captionLink' style='position: absolute; bottom: 0px;' onclick='floatingModule.cancelButton(); return false;' href='#' tip='" + responseObject.demographicCancel + "'>" + responseObject.demographicCancel + "</a></div></div>";
		
		col2.appendChild(profileContentForm);
		
		this.displayModule(modulePanelBD);
		
		hotelsdotcom.innitDemographicForm();
		
		// Analytics
		pageTracker._trackPageview('/statement/module/' + moduleName + '/' + moduleId + '/demographics');
	}
    
    /**
	 * Send Demographics
	 * 
	 */
	this.saveDemographics = function ()
	{
		var postData = '';

		//hotels.com module uid
        postData += '[module_uid]='+moduleUid;

		//fetch all statments with choices elements
		var statementAndChoices = document.getElementById('statementChoices').childNodes;

		if(statementAndChoices){
			
			for(var i=0; i < statementAndChoices.length; i++ ){
				
				postData += '&[resp-'+ statementAndChoices[i].getAttribute('id') +']=' + statementAndChoices[i].getAttribute('value');

			}
			
		}
        
		var genderSet = document.profileContentForm.demog-gender;
		if (genderSet)
		{
			for (var i=0; i<genderSet.length; i++)  {
				
				if (genderSet[i].checked)  {

				gValue = genderSet[i].value

				postData += '&[demog-gender]=' + gValue;

				} 
			}

			
		}

		var tripSet = document.profileContentForm.trip-type;
		if (tripSet)
		{
			for (var i=0; i<tripSet.length; i++)  {
				
				if (tripSet[i].checked)  {

				gValue = tripSet[i].value

				postData += '&[trip-type]=' + gValue;

				} 
			}

			
		}

		var ageSet = document.profileContentForm.demog-age;
		if (ageSet)
		{
			for (var i=0; i<ageSet.length; i++)  {
				
				if (ageSet[i].checked)  {

				gValue = ageSet[i].value

				//postData += '&data[Demographics][age]=' + gValue;

				postData += '&[demog-ageRange]=' + gValue;

				} 
			}

			
		}

		var destinationSet = document.profileContentForm.destination;
		if (destinationSet)
		{

			for (var i=0; i<destinationSet.length; i++)  {
				
				if (destinationSet[i].selected)  {

				gValue = destinationSet[i].value

				postData += '&[data-destination]=' + gValue;

				} 
			}

			
		}

		var supriseSet = document.profileContentForm.suprise-me;
		if (supriseSet)
		{		
				if(supriseSet.checked){
				
					postData += '[suprise-me]=1';
				}
		}


		//var callback =
		//{
		//	success: this.onSaveDemographics, 
		//	failure: this.ajaxFailure,
		//	cache: false
		//};
		
		//var cObj = YAHOO.util.Connect.asyncRequest('POST', '/settings/demographic_updates/' + moduleId, callback, postData);

		//new call
                
		var cObj = $.ajax({ 
			type: 'POST',
			//url: '/statement/demographic_updates/'+ moduleId,
			url: 'http://finish.visualdna.com/finish.php',
			data: postData,
			//dataType: 'json',
			success: this.onSaveDemographics,
			failure: this.ajaxFailure,
			cache: false
		
		});
        
        
	}
    
    /**
     * Callback function called when demographics are saved
     *
     */
    this.onSaveDemographics = function (o)
    {
		alert(o);
        alert(o.responseText);
        eval(o.responseText);
		//if (demographicsSaved == 1)
		//{
			// all good... create processing page, and redirect to results page
            //floatingModule.createProcessingPage(resultsPage);            
			floatingModule.createProcessingPage('/party/results/017b814cf2c6245745c18a73abb32aqs');
		//}
    }
    
    /**
	 * Create processing page
	 * 
	 */
	this.createProcessingPage = function (resultsPage)
	{		
		var modulePanelBD = document.createElement('div');
		modulePanelBD.setAttribute('id', 'modulePanelBD');
        // This is an IE-safe equivalent of doing innerHTML = '';
		while (modulePanelBD.hasChildNodes()) modulePanelBD.removeChild(modulePanelBD.firstChild);
        
		var inner = document.createElement('div');
		inner.setAttribute('id', 'inner');
		inner.className = 'inner';
        
		modulePanelBD.appendChild(inner);
		
		var process = document.createElement('div');
		process.setAttribute('id', 'moduleProcess');
		inner.appendChild(process);
        
		//if (YAHOO.env.ua.ie && YAHOO.env.ua.ie <= 6)
		if ($.browser.msie && $.browser.version <= 6)

		{
			process.innerHTML = "<img src='/img/module/loader_circles_02a_forgif.gif' />";
		}
        else
		{
			process.innerHTML = '<object width="115" height="100"><param name="movie" value="/swf/module/loader_circles.swf"><embed src="/swf/module/loader_circles.swf" width="115" height="100"></embed></object>';	
		}
		
		this.displayModule(modulePanelBD);
		window.location = resultsPage;
	}
	
    /**
	 * Ajax Failure - usually happens when the error occurs server side and a 500 response is returned. GTB HACK?
	 * 
	 */
	this.ajaxFailure = function (o)
	{
		if (o.status > -1) // if not user abort
		{
			alert("We're sorry, an error occurred! Please try again.");
		}
	}
    
    /**
	 * Cancel the module and return
	 *
	 */
	this.cancelButton = function ()
	{
		window.location = '/';
	}
	
	/**
	 * Redo module
	 *
	 */
	this.redoModule = function ()
	{        
		window.location = '/statement/module/'+ moduleName + '/' + moduleId;
	}
    
}


