/* 
 This file was generated by Dashcode.  
 You may edit this file to customize your widget or web page 
 according to the license.txt file included in the project.
 */

//
// This template also demonstrates how to make use of client-side database storage to store content that can be used, whether the application is online or offline.
// The database has one trivial table: a simple key-value table. You can imagine yourself having different tables with different columns, if you are familiar with relational database concepts.
//
// On devices that doesn't have the local database feature, the settings will not be remembered.
//

var database = null;                            // The client-side database
var DB_tableName = "SimpleKeyValueTable";       // database name
var originalSettings = {};                      // original message and settings, in case there is no client side database

//
// Function: load()
// Called by HTML body element's onload event when the web application is ready to start
//
function load()
{
    // JJR Detect
    if (!DetectWebkit()) {
        window.location = "noworky.html";
    } else {
        //alert("Wowoo - this is a compatible browser");
    }
/*
    var element = document.getElementById('message');
    if (element) {
        originalSettings.message = element.value;
        originalSettings.color = 'black'; // We only have a limited set of color chips, so use 'black' here.
        var fontSettings = getFontSettingsFromElement(element);
        originalSettings.fontFamily = fontSettings.fontFamily;
        originalSettings.fontSize = fontSettings.fontSize;
        element.value = '';
    }
    
    dashcode.setupParts();
    
    initDB();
    if (!database) {
        element.value = originalSettings.message;
    }
    
    */
}

//
// Function: flipToFront(event)
// Flip to the front view to show the normal utility view
//
function flipToFront(event)
{
    var views = document.getElementById('views');
    var front = document.getElementById('front');
    if (views && views.object && front) {
        views.object.setCurrentView(front, true);
    }
}

//
// Function: flipToSettings(event)
// Flip to the back view to present user customizable settings
//
function flipToSettings(event)
{
    var views = document.getElementById('views');
    var settings = document.getElementById('settings');
    if (views && views.object && settings) {
        views.object.setCurrentView(settings);
    }
}
/*
//
// Function: initDB()
// Init and create the local database, if possible
//
function initDB()
{
    try {
        if (window.openDatabase) {
            database = openDatabase("Message", "1.0", "Message Database", 1000);
            if (database) {
                database.transaction(function(tx) {
                    tx.executeSql("SELECT COUNT(*) FROM " + DB_tableName, [],
                    function(tx, result) {
                        loadMessage();
                    },
                    function(tx, error) {
                        // Database doesn't exist. Let's create one.
                        tx.executeSql("CREATE TABLE " + DB_tableName +
                        " (id INTEGER PRIMARY KEY," +
                        "  key TEXT," +
                        "  value TEXT)", [], function(tx, result) {
                            initMessage();
                            loadMessage();
                        });
                    });
                });
            }
        }
    } catch(e) {
        database = null;
    }
}

//
// Function: showError(errorString)
// Show an error
//
// errorString: string to be displayed
//
function showError(errorString)
{
    var element = document.getElementById('message');
    element.value = errorString;
    element.setAttribute('style', 'font-family: Helvetica; font-weight: bold; color: rgb(178, 6, 40);');
}

//
// Function: cleanTable()
// Utility function to clean table. It can be used to test table re-creation
//
function cleanTable()
{
    try {
        if (window.openDatabase) {
            database = openDatabase("Message", "1.0", "Message Database");
            if (database) {
                database.transaction(function(tx) {
                    tx.executeSql("DROP TABLE " + DB_tableName, []);
                });
            }
        }
    } catch(e) { 
    }
}

//
// Function: clearSettings()
// Reset settings to default
//
function clearSettings(event)
{
    if (database) {
        database.transaction(function(tx) {
            tx.executeSql("DELETE FROM " + DB_tableName, [],
            function(tx, result) {
                initMessage();
                loadMessage();
            },
            function (tx, error) {
                showError("Can't reset database");
            });
        });
    }
    else {
        initMessage();
        loadMessage();
    }
}

//
// Function: getFontSettingsFromElement(element)
// Get font family and size of an element
//
function getFontSettingsFromElement(element)
{
    var computedStyle = document.defaultView.getComputedStyle(element, null);
    var returnValue = {};
    
    returnValue.fontFamily = computedStyle.getPropertyValue("font-family");
    // Simplistic matching of font names like 'Marker Felt'
    try {
        if (returnValue.fontFamily.charAt(0) == "'") {
            returnValue.fontFamily = returnValue.fontFamily.substring(1, returnValue.fontFamily.length-1);
        }
    }
    catch (e) {}
    
    returnValue.fontSize = computedStyle.getPropertyValue("font-size");
    
    return returnValue;
}

//
// Function: initMessage()
// Initialize the message string to defaults. If there is database, the initialization values will be saved as well.
//
function initMessage()
{
    var element = document.getElementById('message');
    if (!element) return;
    
    // Clean inline styles so that external styles can be applied during init
    element.style.fontFamily = '';
    element.style.fontSize = '';
    element.value = originalSettings.message;
    
    if (database) {
        database.transaction(function (tx) {
            tx.executeSql("INSERT INTO " + DB_tableName + " (id, key, value) VALUES (?, ?, ?)", [0, 'message', originalSettings.message]);
            tx.executeSql("INSERT INTO " + DB_tableName + " (id, key, value) VALUES (?, ?, ?)", [1, 'font-family', originalSettings.fontFamily]);
            tx.executeSql("INSERT INTO " + DB_tableName + " (id, key, value) VALUES (?, ?, ?)", [2, 'font-size', originalSettings.fontSize]);
            tx.executeSql("INSERT INTO " + DB_tableName + " (id, key, value) VALUES (?, ?, ?)", [3, 'color', originalSettings.color]);
        });
    }
}

//
// Function: updateColorChip()
// Update the settings UI so that the correct color chip is selected
//
// color: the new color
//
function updateColorChip(color)
{
    var checkMark = document.getElementById('checkMark');
    if (checkMark) {
        var colorChip = document.getElementById(color+'ColorChip');
        if (colorChip) {
            setTimeout(function() {
                checkMark.style.left = document.defaultView.getComputedStyle(colorChip, null).getPropertyValue('left');
            }, 0);
            document.getElementById('message').style.color = color;
        }
    }
}

//
// Function: updateSelectValue(selectElement, value)
// Update the settings UI so that the right popup value is selected
//
// selectElement: the element with the popup
// value: the new value
//
function updateSelectValue(selectElement, value)
{
    var options = selectElement.options;
    var i = 0;
    for (; i < options.length; i++) {
        if (options.item(i).value == value) break;
    }
    if (i < options.length) {
        selectElement.selectedIndex = i;
    }
}

//
// Function: loadMessage()
// Load saved message and settings from the database. If there is no local database, we just use element's original properties
//
//
function loadMessage()
{
    var element = document.getElementById('message');
    
    if (database) {
        database.transaction(function(tx) {
            tx.executeSql("SELECT key, value FROM " + DB_tableName, [],
            function(tx, result) {
                for (var i = 0; i < result.rows.length; ++i) {
                    var row = result.rows.item(i);
                    var key = row['key'];
                    var value = row['value'];

                    if (key == 'message') {
                        element.value = value;
                    }
                    else {
                        element.style[key] = value;
                        if (key == 'font-family') {
                            updateSelectValue(document.getElementById('fontFamily'), value);
                        }
                        else if (key == 'font-size') {
                            updateSelectValue(document.getElementById('fontSize'), value);
                        }
                        else if (key == 'color') {
                            updateColorChip(value);
                        }
                    }
                }
            },
            function(tx, error) {
                showError('Failed to retrieve stored information from database - ' + error.message);
            });
        });
    }
    else {
        // Load defaults
        updateColorChip(originalSettings.color);
        updateSelectValue(document.getElementById('fontFamily'), originalSettings.fontFamily);
        updateSelectValue(document.getElementById('fontSize'), originalSettings.fontSize);
    }
}

//
// Function: messageChanged(event)
// Update the database when user changed the message
//
//
function messageChanged(event)
{
    if (database) {
        var element = document.getElementById('message');
        database.transaction(function (tx) {
            tx.executeSql("UPDATE " + DB_tableName + " SET key = 'message', value = ? WHERE id = 0", [element.value]);
        });
    }
}

//
// Function: fontFamilyChanged(event)
// Update the database when user changed the font family setting
//
//
function fontFamilyChanged(event)
{
    var value = document.getElementById('fontFamily').value;
    document.getElementById('message').style.fontFamily = value;
    
    if (database) {
        database.transaction(function (tx) {
            tx.executeSql("UPDATE " + DB_tableName + " SET key = 'font-family', value = ? WHERE id = 1", [value]);
        });
    }
}

//
// Function: fontSizeChanged(event)
// Update the database when user changed the font size setting
//
//
function fontSizeChanged(event)
{
    var value = document.getElementById('fontSize').value;
    document.getElementById('message').style.fontSize = value;
    
    if (database) {
        database.transaction(function (tx) {
            tx.executeSql("UPDATE " + DB_tableName + " SET key = 'font-size', value = ? WHERE id = 2", [value]);
        });
    }
}

//
// Function: colorChanged(event)
// Update the database when user changed the color setting
//
//
function colorChanged(event)
{
    var element = event.target.parentNode;
    var index = element.id.indexOf('ColorChip');
    var color = element.id.substring(0, index);
    updateColorChip(color);
    
    if (database) {
        database.transaction(function (tx) {
            tx.executeSql("UPDATE " + DB_tableName + " SET key = 'color', value = ? WHERE id = 3", [color]);
        });
    }
}

*/

// ****************************** JJR Custom ******************************
/* This might be useful to track what the current and previous input box was
// Now. jActiveElement, and jOldActiveElement will point to the previous box
// Limitation: this is only valid after the new box has focus.  The blur
// event doesn't know about the new box yet.
// http://ajaxandxml.blogspot.com/2007/11/emulating-activeelement-property-with.html
var jOldActiveElement;
var jActiveElement;
function _dom_trackActiveElement(evt) {
  //if (evt && evt.target) { 
  if (evt) { 
    jActiveElement = evt.target == document ? null : evt.target;
        
    var ObjLbl = document.getElementById("jLblDebug");
    ObjLbl.innerHTML= ObjLbl.innerHTML +":" + jActiveElement.id ;
         
  } 
}
 
function _dom_trackActiveElementLost(evt) { 
    var ObjLbl = document.getElementById("jLblBlur");
        ObjLbl.innerHTML= ObjLbl.innerHTML + ":"+ jActiveElement.id;
    jOldActiveElement = jActiveElement; 
    jActiveElement = null;     
    
}

document.addEventListener("focus",_dom_trackActiveElement,true);
document.addEventListener("blur",_dom_trackActiveElementLost,true);

*/

//****************************  jKeyboardGotDismissed() & jKeyboardGotShown() -BEGIN- ******************************
// This snippet give you a reasonable way to detect that the user is not currently input data.
// Motivation:  On the iphone, when inputing data, the soft keyboard pops up.  When the keyboard is dismissed, it doesn't
// usually scoll back to the original position.
// 
// I know this is kludgy.  There is probably some slick way to detect that a input box lost focus, but that it had
// moved on to onother input box, or not - but I couldn't find any examples.  This uses a timer, and seems to fall
// into the good-enough category.
//
// Insturctions:
//  Copy this block of code into your script
//  Modify jKeyboardGotDismissed() & jKeyboardGotShown() as desired.
// 
// Use Cases:
//      Make sure the screen has scolled to 0,0 after the user finishes inputing data on the iphone
//          add something like " window.scrollTo(0, 0) " to jKeyboardGotDismissed()
var bStoppedInputtingUnlessSomeoneTellsMeOtherwise = true;
var enumKeyboardStateThereGone = "Gone";//There, means the keyboard must be visible, "Gone" means it must be hidden
function _jFocusTypeHelper() {
    if (bStoppedInputtingUnlessSomeoneTellsMeOtherwise == true) {
        if (enumKeyboardStateThereGone == "There") {
            enumKeyboardStateThereGone = "Gone";    
            jKeyboardGotDismissed();
        } else {
            enumKeyboardStateThereGone = "Gone";// why twice? Just so enumKeyboardStateThereGone will be set before the function call.
        }
        
    } else {
        if (enumKeyboardStateThereGone == "Gone" ) {
            enumKeyboardStateThereGone = "There";
            jKeyboardGotShown();
        } else {
            enumKeyboardStateThereGone = "There"; // why twice? Just so enumKeyboardStateThereGone will be set before the function call.
        }
        
    }
}
 
// This function gets called whenever the keyboard is  dismissed.  feel free to modify it
// Motivation: I wanted to make sure the screen scolled back to the right spot after the last input
// Known Limitations: 1/4 second delay before jKeyboardGotDismissed is notified.
function jKeyboardGotDismissed() {
    //alert("The soft Keyboard just got dismissed (if, in fact, this device has a softkeyboard)");
     window.scrollTo(0, 0);//Scroll home after the keyboard is dismissed.  Delete this line if you don't want that to happen.  @TODO: Add smooth scrooling
}

function jKeyboardGotShown() {
    //alert("The soft Keyboard must have just popped up (if, in fact, this device has a softkeyboard)");
}

document.addEventListener("blur",function() {bStoppedInputtingUnlessSomeoneTellsMeOtherwise=true;setTimeout(_jFocusTypeHelper,250);},true);
document.addEventListener("focus",function() {bStoppedInputtingUnlessSomeoneTellsMeOtherwise=false;_jFocusTypeHelper();},true);

//****************************  jKeyboardGotDismissed() & jKeyboardGotShown() -END- ******************************




// from: http://www.ezsurvey.com/samplesize.html
function ProbCriticalNormal(P)
{
//      input p is confidence level convert it to
//      cumulative probability before computing critical

	var   Y, Pr,	Real1, Real2, HOLD;
	var  I;
	var PN = [0,    // ARRAY[1..5] OF REAL
			-0.322232431088  ,
			 -1.0             ,
			 -0.342242088547  ,
			 -0.0204231210245 ,
			 -0.453642210148E-4 ];

	var QN = [0,   //  ARRAY[1..5] OF REAL
			0.0993484626060 ,
			 0.588581570495  ,
			 0.531103462366  ,
			 0.103537752850  ,
			 0.38560700634E-2 ];

	 Pr = 0.5 - P/2; // one side significance


  if ( Pr <=1.0E-8) HOLD = 6;
	else {
			if (Pr == 0.5) HOLD = 0;
			else{
					Y = Math.sqrt ( Math.log( 1.0 / (Pr * Pr) ) );
					Real1 = PN[5];  Real2 = QN[5];

					for ( I=4; I >= 1; I--)
					  {
						  Real1 = Real1 * Y + PN[I];
						  Real2 = Real2 * Y + QN[I];
						}

					HOLD = Y + Real1/Real2;
					} // end of else pr = 0.5
			 } // end of else Pr <= 1.0E-8

		return HOLD;
}  // end of CriticalNormal

function SampleSize(margin,  confidence,  response,  population)
{
     pcn = ProbCriticalNormal(confidence / 100.0);
     d1 = pcn * pcn * response * (100.0 - response);
     d2 = (population - 1.0) * (margin * margin) + d1;
    if (d2 > 0.0)
     return Math.ceil(population * d1 / d2);
    return 0.0;
}

function MarginOfError( sample,  confidence,  response,  population)
{
     var pcn = ProbCriticalNormal(confidence / 100.0);
     d1 = pcn * pcn * response * (100.0 - response);
     d2 = d1 * (population - sample) / (sample * (population - 1.0))
    if (d2 > 0.0)
     return Math.sqrt(d2);
    return 0.0;
}

function DoCalculate()
{	
var ss = SampleSize(Number(document.getElementById("margin").value),
		    Number(document.getElementById("confidence").value), 
		    Number(document.getElementById("response").value), 
		    Number(document.getElementById("population").value));
    var r = document.getElementById("responserate").value/100.0; 
    var NumSurveys = ss/r;
	document.getElementById('jLblAnswer').innerHTML=('<b>'+Math.ceil(NumSurveys).toString()+'</b');
	
	/*ss = SampleSize(Number(document.getElementById("margin").value),
		    Number(document.getElementById("confidence1").value), 
		    Number(document.getElementById("response").value), 
		    Number(document.getElementById("population").value));
	document.getElementById('sample4').innerHTML=('<b>'+Math.ceil(ss).toString()+'</b');
	
	ss = SampleSize(Number(document.getElementById("margin").value),
		    Number(document.getElementById("confidence2").value), 
		    Number(document.getElementById("response").value), 
		    Number(document.getElementById("population").value));
	document.getElementById('sample5').innerHTML=('<b>'+Math.ceil(ss).toString()+'</b');
	
	ss = SampleSize(Number(document.getElementById("margin").value),
		    Number(document.getElementById("confidence3").value), 
		    Number(document.getElementById("response").value), 
		    Number(document.getElementById("population").value));
	document.getElementById('sample6').innerHTML=('<b>'+Math.ceil(ss).toString()+'</b');

	var m = MarginOfError(Number(document.getElementById("sample1").value),
		    Number(document.getElementById("confidence").value), 
		    Number(document.getElementById("response").value), 
		    Number(document.getElementById("population").value));
	document.getElementById('margin1').innerHTML=('<b>'+m.toFixed(2).toString()+'%</b');
		    
	m = MarginOfError(Number(document.getElementById("sample2").value),
		    Number(document.getElementById("confidence").value), 
		    Number(document.getElementById("response").value), 
		    Number(document.getElementById("population").value));
	document.getElementById('margin2').innerHTML=('<b>'+m.toFixed(2).toString()+'%</b');
		    
	m = MarginOfError(Number(document.getElementById("sample3").value),
		    Number(document.getElementById("confidence").value), 
		    Number(document.getElementById("response").value), 
		    Number(document.getElementById("population").value));
	document.getElementById('margin3').innerHTML=('<b>'+m.toFixed(2).toString()+'%</b');
*/
    jDoNag();
	return true;
}

//*** called whenever input changed
function jClearInputs(event) {
    var ObjLblX1 = document.getElementById("jLblAnswer");
    ObjLblX1.innerHTML = "";
}



//usage: 
/*
tr><td colspan="2" style=""><b>Input Filter</b></td></tr> 
<tr><td>Numbers Only<br><span class="comment">(No Decimal Point)</span></td><td><input class="inputField" type="text" onKeyPress="return filterInput(1, event)" name="numOnly" value="0123456789"></td></tr> 
<tr><td>Numbers Only<br><span class="comment">(With Decimal Point)</span></td><td><input class="inputField" type="text" onKeyPress="return filterInput(1, event, true)" name="numOnly" value="56789.01234"></td></tr> 
<tr><td>Alphabets Only</td><td><textarea class="inputField" onKeyPress="return filterInput(0, event)" name="alphaOnly1">ABCDEFGHIJKLMNOPQRSTUVWXYZ 
abcdefghijklmnopqrstuvwxyz</textarea></td></tr> 
<tr><td>Alphabet Numeric</td><td><textarea class="inputField" onKeyPress="return filterInput(2, event)" name="alphaNumeric">ABCDEFGHIJKLMnopqrstuvwxyz 
0123456789</textarea></td></tr> 
<tr><td>Alphabet Numeric<br><span class="comment">(With Custom characters [ .])</span></td><td><textarea class="inputField" onKeyPress="return filterInput(2, event, false, ' .')" name="alphaNumCustom1">Test this...</textarea></td></tr> 
<tr><td>Alphabet Numeric<br><span class="comment">(With Custom characters [@ _ .])</span></td><td><textarea class="inputField" onKeyPress="return filterInput(2, event, false, '@_-.')" name="alphaNumCustom2">some_body@some-domain.com</textarea></td></tr> 
*/

//see: http://www.weberdev.com/get_example-4437.html
function jFilterInput(filterType, evt, allowDecimal, allowCustom){ 
    var keyCode, Char, inputField, filter = ''; 
    var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
    var num   = '0123456789'; 
    var neg = '-'; // negative sign
    // Get the Key Code of the Key pressed if possible else - allow 
    if(window.event){ 
        keyCode = window.event.keyCode; 
        evt = window.event; 
    }else if (evt)keyCode = evt.which; 
    else return true; 
    // Setup the allowed Character Set 
    if(filterType == 0) filter = alpha; 
    else if(filterType == 1) filter = num; 
    else if(filterType == 2) filter = alpha + num; 
    else if(filterType == 3) filter = neg + num; //jjr
    if(allowCustom)filter += allowCustom; 
    if(filter == '')return true; 
    // Get the Element that triggered the Event 
    inputField = evt.srcElement ? evt.srcElement : evt.target || evt.currentTarget; 
    // If the Key Pressed is a CTRL key like Esc, Enter etc - allow 
    if((keyCode==null) || (keyCode==0) || (keyCode==8) || (keyCode==9) || (keyCode==13) || (keyCode==27) )return true; 
    // Get the Pressed Character 
    Char = String.fromCharCode(keyCode); 
    // If the Character is a number - allow 
    if((filter.indexOf(Char) > -1)) return true; 
    // Else if Decimal Point is allowed and the Character is '.' - allow 
    else if(filterType == 1 && allowDecimal && (Char == '.') && inputField.value.indexOf('.') == -1)return true; 
    else return false; 
}


//*********************** Nag -BEGIN- *****************************************
var StrTarget = "SurveySize";
var StrProductPage = "about" + StrTarget.toLowerCase();
var EnumSource = (jIsEmbedded()) ? "Phonegap" : "Webapp";


function jBuyNowItunes() {
    // Break out of iframe if you're in it.  Motivation:  If I'm in my simulator iframe, then i won't be able to get to the itunes because of javascript security and something with the itunes rediect
    /*if (top.location != location) {
        top.location.href = document.location.href ;
     }
    */
    var StrUrl = "http://app.eleganttechnologies.com/php/app/eg/prod/html/ItunesRedirect.php?"+StrTarget+"&StrTarget="+StrTarget+"&EnumSource="+EnumSource;
    //var StrUrl = "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=303786428&mt=8";
    document.location.href = StrUrl;
}


function jBuyNowAndroid() {
    var StrUrl = "http://www.cyrket.com/package/com.eleganttechnologies."+StrTarget.toLowerCase();
    if (top.location != location) {
        window.open(StrUrl,'mywindow')
     } else {
        window.location = StrUrl;
    }
}


function jGotoProductHomepage() {
    var StrUrl = "http://www.eleganttechnologies.com/"+StrProductPage
    if (top.location != location) {
        window.open(StrUrl,'mywindow')
     } else {
        window.location = StrUrl;
    }
}

function _jDoNag(){
    flipToSettings();//legacy from building a utility widget
}



function jDoNag(){
    if (!jIsEmbedded()) {
        // state: using free version
        //if (DetectIphoneOrIpod() ) {
            setTimeout(_jDoNag,5000); 
        //}
    } 
}
//*********************** Nag -END-   *****************************************


//*********************** PhoneGap Help Functions -BEGIN- *********************
// Motivation:  I made a web app that I wanted to use the same code on the web and in phonegap.  I'm using this to turn on/off corresponding behavior, like telling the web user about the phonegap version
// @Authors: JJBigThoughts 
function jIsEmbedded() {
     if (window.Device !== undefined) { // tate: is Phonegap
        return true;
    } else {
        try {
            so = device.getServiceObject("Service.SysInfo", "ISysInfo");  // detect nokia
            return true;
        } catch (e) {
            return false;
        }
    }
}
//*********************** PhoneGap Help Functions -END- *********************



//*********************** Browser Detection Functions -BEGIN- *********************
function jIsSafari() {
    if(/Safari/.test(navigator.userAgent))  
        return true;
    else 
        return false;
}


function jIsMac() {
    if(/Mac/.test(navigator.userAgent))  
        alert('mac');//return true;
    else 
        alert('not mac');//return false;
}

function jGetSafari(event) {
    window.location = "http://www.apple.com/safari/download/";
}
//*********************** Browser Detection Functions -END- *********************



//*********************** Scroll Stuff -BEGIN- *********************
// don't scroll ever on an iphone, but its ok on android
// http://phonegap.pbwiki.com/Preventing-Scrolling-on-iPhone-Phonegap-Applications-->
// Also make sure to modify index.html
/*
    <body>
    <div id="container" ontouchmove="touchMove(event);">
    content goes here
    </div>
    </body>
*/
touchMove = function(event) {
alert('moving');
    if (DetectIphoneOrIpod()) {
        event.preventDefault();
    } // else  scroll on android and desktop
}
//*********************** Scroll Stuff -END- *********************
