﻿/****************************************************
        Main MoodMaps Javascript Function File
        
               Author: Steven Gray
              Version: 0.1
                 Date: 09/10/2009

*****************************************************/

var gridDeltaDegs = 4;

/*  Add Field ---------------------------------------*/
function addField(field,area,limit) {
    if(!document.getElementById) return; //Stop older browsers and blocked javascript.
    var field_area = document.getElementById(area);
    var all_inputs = field_area.getElementsByTagName("input"); //Get all the input fields in the given area.
    
    //Find the count of the last element of the list. It will be in the format '<field><number>'.
    var last_item = all_inputs.length - 1;
    var last = all_inputs[last_item].id;
    var count = Number(last.split("_")[1]) + 1;

    //If the maximum number of elements have been reached, exit.
    if(count > limit && limit > 0) return;

    if(document.createElement) {
        var li = document.createElement("li");
        var input = document.createElement("input");
        input.id = field+count;
        input.name = field+count;
        input.type = "text";
        li.appendChild(input);
        field_area.appendChild(li);
    } else {
        field_area.innerHTML += "<li><input name='"+(field+count)+"' id='"+(field+count)+"' type='text' /></li>";
    }
    return false; 
}

/*  Create Fields ---------------------------------------*/           
function createFields(numValue, area, limit){
      if(!document.getElementById) return;
      
      // Clear the area
      
      // Minus 1 reflects the single element we have on the page!
      var num = (document.getElementById(numValue).value) - 1 ;
      
      var field_area = document.getElementById(area);
      var field = "quest_";
      var count = 0; 
      
      var all_inputs = field_area.getElementsByTagName("input");
    
      if(all_inputs == 0){
          count = 0
      }else{
          count = all_inputs.length;
      }
       
      //Make sure count does not exceed limit and not null
      if((count > limit && limit >= 0)) return;
          
      if(document.createElement) {
            var i = 0;
            for(i=0;i<num;i++){         
                if((count <= num)){
                    var li = document.createElement("li");
                    var input = document.createElement("input");
                    input.id = field+count;
                    input.name = field+count;
                    input.type = "text";
                    li.appendChild(input);
                    field_area.appendChild(li);
                    count++;
                }
            }  
       } else {
           //Earlier versions of JavaScript
           //field_area.innerHTML += "<li><input name='"+(field+count)+"' id='"+(field+count)+"' type='text' /></li>";
       }
}

function countdown_clock(year, month, day, hour, minute, format) {
    html_code = '<span id="countdown" style="font-weight: bold;"></span>';
    document.write(html_code);
    countdown(year, month, day, hour, minute, format);
}

function countdown(year, month, day, hour, minute, format, suffixStart) {
    Today = new Date();
    Todays_Year = Today.getFullYear() - 2000;
    Todays_Month = Today.getMonth();

    var suffixText = ' until the end of this survey.';

    if (suffixStart == 1) {
        suffixText = ' until the start of this survey.';
    } 
    

    //Convert both today's date and the target date into miliseconds.                           
    Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),
                     Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();
    Target_Date = (new Date(year, month - 1, day, hour, minute, 00)).getTime();

    //Find their difference, and convert that into seconds.                  
    Time_Left = Math.round((Target_Date - Todays_Date) / 1000);

    //alert(Time_Left + ' seconds!');

    if (Time_Left < 0)
        Time_Left = 0;

    switch (format) {
        case 0:
            //The simplest way to display the time left.
            jQuery('#countdownTimer').replaceWith('<span id="countdownTimer"><b>' + Time_Left + ' seconds' + '</b>' + suffixText + '</span>');
            break;
        case 1:
            //More datailed.
            days = Math.floor(Time_Left / (60 * 60 * 24));
            Time_Left %= (60 * 60 * 24);
            hours = Math.floor(Time_Left / (60 * 60));
            Time_Left %= (60 * 60);
            minutes = Math.floor(Time_Left / 60);
            Time_Left %= 60;
            seconds = Time_Left;

            dps = 's'; hps = 's'; mps = 's'; sps = 's'; zeros = '0'; zerom = '0';
            //ps is short for plural suffix.
            if (days == 1) dps = '';
            if (hours == 1) hps = '';
            if (minutes == 1) mps = '';
            if (seconds == 1) sps = '';
            if (seconds > 9) zeros = '';
            if (minutes > 9) zerom = '';

            var time = '' + days + ' day' + dps + ' ';
            time += hours + ':';
            time += zerom + minutes + ':';
            time += zeros + seconds + '';

            jQuery('#countdownTimer').replaceWith('<span id="countdownTimer"><b>' + time + '</b>' + suffixText + '</span>');

            break;
        default:
            var time = Time_Left + ' seconds';
            jQuery('#countdownTimer').replaceWith('<span id="countdownTimer"><b>' + time + '</b>' + suffixText + '</span>');
    }
}

function clearAndFocus(el){
    el.value = '';
    el.focus()
}

function clearText() {
    if (document.searchForm.searchbar.value == "Enter your Search Query")
      document.searchForm.searchbar.value = "";
   
}

function resetText() {
    if (document.searchForm.searchbar.value == "")
        document.searchForm.searchbar.value = "Enter your Search Query";
}


// ***************************************************************************************
//                  Google Map Code
// ***************************************************************************************

function getOverlay(tileService, descriptor) {
    //return the GOverlay object (e.g. GTileLayerOverlay) to put this object onto a GMap2
    var copyrightCollection = new GCopyrightCollection("© ");
    
    copyrightCollection.addCopyright(
          new GCopyright("MapTubeD CASA",
          new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)),
         0,
          "<a href=\"http://www.casa.ucl.ac.uk\">CASA</a>")
    );

    var tileLayer = new GTileLayer(copyrightCollection);
    tileLayer.tileRequestPattern = tileService.replace("\x7B0\x7D", descriptor); //{0} in hex escape characters
    tileLayer.getOpacity = function() { return 1.0; }
    tileLayer.getTileUrl = function(a, b) {
        //converts tile x,y into keyhole string
        var c = Math.pow(2, b);
        var d = a.x;
        var e = a.y;
        var f = "t";
        for (var g = 0; g < b; g++) {
            c /= 2;
            if (e < c) {
                if (d < c) { f += "q" }
                else { f += "r"; d -= c }
            }
            else {
                if (d < c) { f += "t"; e -= c }
                else { f += "s"; d -= c; e -= c }
            }
        }
        return this.tileRequestPattern.replace("\x7B1\x7D", f); //{1} in hex escape characters
    };
    tileLayer.isPng = function() { return true; };
    return new GTileLayerOverlay(tileLayer);
}





/***********************************************************************************
                        GOOGLE VISUALISATION
*************************************************************************************/

function drawSurveyOverViewChart(feedURL) {
    jQuery.ajaxSetup({ 'async': false });

    var gData = new google.visualization.DataTable();
    gData.addColumn('string', 'Date');
    gData.addColumn('number', 'Total Number of Responses');

    jQuery.getJSON(feedURL + '/' + surveyID + '/' + questID + '/ResponseGraphData', function(jSONData) {
        gData.addRows(jSONData.responseTotal);


        jQuery.each(jSONData.dateTime, function(i, item) {
            gData.setValue(i, 0, item);
        });

        jQuery.each(jSONData.counts, function(i, item) {
            gData.setValue(i, 1, item);
        });
    });

    var chart = new google.visualization.LineChart(document.getElementById('responsesOverTime'));
    chart.draw(gData, { width: 800, height: 300, legend: 'bottom', title: '' });
}


function drawSurveyOverViewPieChart(feedURL) {
    var gData = new google.visualization.DataTable();
    gData.addColumn('string', 'Title');
    gData.addColumn('number', 'Responses');

    jQuery.ajaxSetup({ 'async': false });
    jQuery.getJSON(feedURL + '/' + surveyID + '/' + questID + '/PieChartData', function(jSONData) {
        gData.addRows(jSONData.title.length);

        jQuery.each(jSONData.title, function(i, item) {
            gData.setValue(i, 0, item);
        });

        jQuery.each(jSONData.counts, function(i, item) {
            gData.setValue(i, 1, item);
        });
    });
    
    var chart = new google.visualization.PieChart(document.getElementById('pieChart'));
    chart.draw(gData, { width: 500, height: 240, is3D: true, title: '', legend: 'right', legendFontSize: 12, colors: cKeyArray });
}

function drawQuestionBarGraph(feedURL) {
    var gData = new google.visualization.DataTable();
    gData.addColumn('string', 'Title');
    gData.addColumn('number', 'Responses');

    jQuery.ajaxSetup({ 'async': false });
    jQuery.getJSON(feedURL + '/' + surveyID + '/' + questID + '/BarGraphData', function(jSONData) {
        gData.addRows(jSONData.title.length);

        jQuery.each(jSONData.title, function(i, item) {
            gData.setValue(i, 0, item);
        });

        jQuery.each(jSONData.counts, function(i, item) {
            gData.setValue(i, 1, item);
        });
    });

    var chart = new google.visualization.ColumnChart(document.getElementById('pieChart'));
    chart.draw(gData, { width: 500, height: 240, title: '', legend: 'none', legendFontSize: 8, colors: cKeyArray });
}

function topTen(feedURL, surveyID, questionID) {
    jQuery.getJSON(feedURL + '/' + surveyID + '/' + questionID + '/TopTenGeoCodes', function(data) {
        //Clear Contents
        var rows = '';
        jQuery.each(data.pCode, function(i, item) {
        rows += '<tr><td align="left">' + item + '</td><td align="center">' + data.counts[i] + '</td><td align="center">' + roundNumber((data.counts[i] / data.responseTotal) * 100, 2) + '%</td></tr>';
        });
        jQuery('.TTwrapper').html('<table border=0 style="width: 92%; margin: 0 auto; padding: 5px;"><tr><th align="left">GeoCode</th><th>Responses</th><th>Percentage</th></tr>' + rows + '</table>');
    });
}

function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

function rgb2hex(color) {
    if (color.substr(0, 1) === '#') {
        return color;
    }
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);

    var red = parseInt(digits[2]);
    var green = parseInt(digits[3]);
    var blue = parseInt(digits[4]);

    var rgb = blue | (green << 8) | (red << 16);
    return digits[1] + '#' + rgb.toString(16);
};

function serializeColorPickers() {
    var colorPickersArray = jQuery(".colorSelectorInner");

    //Create Array to hold color values
    var color = new Array();

    jQuery.each(colorPickersArray, function(intIndex, objValue) {
        color[intIndex] = jQuery(objValue).css('backgroundColor');
    });

    var serial = "";

    //Set the ColorPickers new Colors
    jQuery.each(color, function(intIndex, objValue) {
        serial += rgb2hex(color[intIndex]) + ',';
    });

    __doPostBack('__Page', serial);
}    

function convertToGridLocation(latlon) {
    latlon = latlon.split(',', 2);

    var fLat = parseFloat(latlon[0]);
    var fLon = parseFloat(latlon[1]);

    var gX = Math.floor((fLon + 180) / parseFloat(gridDeltaDegs));
    var gY = Math.floor((fLat + 90) / parseFloat(gridDeltaDegs));
    var gridString = '(' + gX + '_' + gY + ')';
    jQuery('#gridRef').html(gridString + ' @ ' + gridDeltaDegs + '&deg; grid increments.');
    return gridString;
}

function setCheckedValue(radioObj, newValue) {
    if (!radioObj)
        return;
    var radioLength = radioObj.length;
    if (radioLength == undefined) {
        radioObj.checked = (radioObj.value == newValue.toString());
        return;
    }
    for (var i = 0; i < radioLength; i++) {
        radioObj[i].checked = false;
        if (radioObj[i].value == newValue.toString()) {
            radioObj[i].checked = true;
        }
    }
}

// GLA Custom Park Map Code ---------------------------------------------------------------------------------
// Clickable Map Request for Attributes
function makeRequest(url, parameters, onReady) {
    http_request = false;
    showSpinner();
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }
    if (!http_request) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }
    http_request.onreadystatechange = eval(onReady);
    http_request.open('GET', url + parameters, true);
    http_request.send(null);
}

function alertContents() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            if (http_request.responseText != "") {
                markerVal = new pointObject();
                jQuery(http_request.responseXML).find('featuredata').each(function() {
                    var counter = 0;
                    var areanum = '';
                    var park = '';
                    jQuery(this).find('attr').each(function() {
                        // Get the areaNumber to Change the dropDown
                        if (jQuery(this).attr("atname") == "areakey") {
                            park = jQuery(this).text();
                            markerVal.name = park;
                            changeDropdownValue('GeoQuestion', park);
                        }
                        if (jQuery(this).attr("atname") == "areanum") {
                            areanum = jQuery(this).text();
                            markerVal.num = areanum;
                            //changeDropdownValue('GeoQuestion', areanum);
                        }
                        if (jQuery(this).attr("atname") == "borough") {
                            var borough = jQuery(this).text();
                            markerVal.area = borough;
                            //if (document.getElementById('boroughDDL').value != borough) {
                            changeDropdownValue('boroughDDL', borough);
                            enableElement('GeoQuestion');
                            makeParkJSONRequest(serverURL + '/datafarm.svc/FetchParkJSON?', '&bid=' + urlencode(borough), 'GeoQuestion', surveyMap, false, park, false);
                            //}
                        }
                    });
                    updateGeoCode(markerVal);
                });
            } else {
                updateGeoCode(null);
                resetDropDown('boroughDDL');
                resetDropDown('GeoQuestion');
                hideSpinner();
            }
            
        } else {
            alert('There was a problem with the request. Please try again later or Contact Support@SurveyMapper.com');
            hideSpinner();
        }
    }
}

function makeParkJSONRequest(url, parameters, dropdownList, mapObject, moveMarker, setPark, zoomIntoSelection) {
    jQuery.getJSON(url + parameters, function(data) {
        jQuery.each(data.parkName, function(i, item) {
            //Add each Park to the Park DropDownList with the id Value
            AddItemDropDown(data.parkDisplayName[i], item, dropdownList);
        });

        if (mapObject != null) {
            // Get bounding box from JSON
            var boundingboxarray = new Array(4);
            jQuery.each(data.boundingbox, function(i, item) {
                boundingboxarray[i] = item;
            });

            //Set the Map to new boundingbox
            var bounds = new GLatLngBounds(new GLatLng(boundingboxarray[0], boundingboxarray[1]), new GLatLng(boundingboxarray[2], boundingboxarray[3]));



            //Keep Current Zoom but zoom in if it's the first time!
            if (lastBounds.getCenter().lat() != bounds.getCenter().lat() && lastBounds.getCenter().lng() != bounds.getCenter().lng()) {

                if (!noZoom) {
                    mapObject.setCenter(bounds.getCenter(), mapObject.getBoundsZoomLevel(bounds));
                } else {
                    mapObject.setCenter(bounds.getCenter(), mapObject.getZoom());
                }
                if (moveMarker) {
                    marker_geo.setPoint(bounds.getCenter());
                }
            }

            lastBounds = bounds;



            if (setPark != '' && setPark != null) {
                //alert('AllChange');
                changeDropdownValue('GeoQuestion', setPark);
                noZoom = true;
            }
        }
        hideSpinner();
        //showdiv('GeoQuestion');
        enableElement('GeoQuestion');
        if (document.getElementById('GeoQuestion').options.length == 0) {
            disableElement('GeoQuestion');
        }
    });

    
    
    resetDropDown(dropdownList);

}

function AddItemDropDown(Text, Value, DropdownList) {
    // Create an Option object        
    var opt = document.createElement("option");

    // Add an Option object to Drop Down/List Box
    document.getElementById(DropdownList).options.add(opt);

    // Assign text and value to Option object
    opt.text = Text;
    opt.value = Value;
}

function pointObject() {
    this.area = '';
    this.name = '';
    this.areanum = '';
}

function updateGeoCode(obj) {
    if (obj != null) {
        jQuery("#ParkSelection").val(obj.area + ' -> ' + obj.name);
    } else {
        jQuery("#ParkSelection").val('');
    }
    hideSpinner();
}

function hidediv(id) {
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(id).style.display = 'none';
    }
    else {
        if (document.layers) { // Netscape 4
            document.id.display = 'none';
        }
        else { // IE 4
            document.all.id.style.display = 'none';
        }
    }
}

function showdiv(id) {
    //safe function to show an element with a specified id
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(id).style.display = 'block';
    }
    else {
        if (document.layers) { // Netscape 4
            document.id.display = 'block';
        }
        else { // IE 4
            document.all.id.style.display = 'block';
        }
    }
}

function enableElement(id) {
    document.getElementById(id).disabled = false;
}

function disableElement(id) {
    document.getElementById(id).disabled = true;
}

function showSpinner() {
    showdiv('ajaxSpinner');
    showdiv('refreshLabel');
}

function hideSpinner() {
    hidediv('ajaxSpinner');
    hidediv('refreshLabel');
}

function changeDropdownValue(dropDownListID, valueToChange) {
    document.getElementById(dropDownListID).value = valueToChange
}

function resetDropDown(dropDownListID) {
    document.getElementById(dropDownListID).selectedIndex = 0;
}

function urlencode(str) {
    return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

function ClearOptionsSlow(id) {
    document.getElementById(id).options.length = 0;
}

function ClearOptions(id) {
    var selectObj = document.getElementById(id);
    var selectParentNode = selectObj.parentNode;
    var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
    selectParentNode.replaceChild(newSelectObj, selectObj);
    return newSelectObj;
}

function concatObject(obj) {
    str = '';
    for (prop in obj) {
        str += prop + " value :" + obj[prop] + "\n";
    }
    return (str);
}


function replaceCustomWidthHeight(datafarmAddress, surveyCode) {
    var hdnURL = "<iframe title='SurveyMapper Survey' class='survey_mapper' type='text/html' width='{width}' height='{height}' src='" + datafarmAddress + "/embed/" + surveyCode + "/{width1}/{height1}' frameborder='0'></iframe>";
    var embedTextbox = document.getElementById('embedLink');
 
    var width = parseInt(document.getElementById('embedWidth').value);
    var height = parseInt(document.getElementById('embedHeight').value);

	// Fix the min width!
	if(width < 280 || isNaN(width)){
		width = 280; 
	}
	
	if(isNaN(height)){
		height = 218;
	}
	
	//Build the size based on fixed percentages
	var widthInner = Math.ceil(width * 0.7);
	var heightInner = Math.ceil(height * 0.89);

    var newString = hdnURL.replace(/\{width\}/g, width);
    newString = newString.replace(/\{height\}/g, height);

	newString = newString.replace(/\{width1\}/g, widthInner);
    newString = newString.replace(/\{height1\}/g, heightInner);
	
    embedTextbox.value = newString;
}

jQuery(document).ready(function()
{
    jQuery(".sign_in").click(function()
    {
        jQuery("#sign_box").toggle();
        jQuery(document).keyup(function(event){
            if (event.keyCode == 27) {
                jQuery("#sign_box").hide();
            }
        });
            return false;
    });
    jQuery("body #main").click(function()
    {
        jQuery("#sign_box").hide();
        return false;
    });
});





