var db;
var dbCreated = false;
var hits = 0;
var timestamp = new Date();
var myScroll1, myScroll2, myScroll3, myScroll4, myScroll5, myScroll6, myScrollD1, myScrollD2;

var objDEVICE = [];
var objDEVGALLERY = [];
var objBRAND = [];
var objCOMPARE = [];

var newdevfeed = 'http://www.thephonedatabase.com/feeds/phones/feed.json';
var populardevfeed = 'http://www.thephonedatabase.com/feeds/phones/feed_top.json';
var blogfeed = 'http://www.thephonedatabase.com/feeds/blog/feed.json';
var brandsfeed = 'http://thephonedatabase.com/feeds/brands/index_brands_json.php';
var branddetailfeed = 'http://thephonedatabase.com/feeds/phones/search.php?q=Phones_Made_By_';
var searchfeed = 'http://www.thephonedatabase.com/feeds/phones/search.php';
var specfeed = 'http://www.thephonedatabase.com/feeds/specs/preview.json.php';
var comparefeed = 'http://www.thephonedatabase.com/feeds/specs/compare.json.php';
var randomcomparefeed = 'http://www.thephonedatabase.com/feeds/phones/random_compare.php';

var selectedbrandurl = "Phones_Made_By_Apple";
var selectedtype = 0;
var deviceid = -1;
var cdevimage = '';
var cdevname = '';
var cdevreldate = '';
var selectedimage = -1;
var sharelink = '';
var sharetitle = '';

window.onload = setDefaults;

/*
function loadDB(){
    console.log("DB: Opening...");
    db = window.openDatabase("TPDB", "1.0", "TPDB DB", 500000);
    if (dbCreated){
        db.transaction(check_devicehistory, transaction_error, get_appinfo);
    }else{
    	db.transaction(populateDB, transaction_error, transaction_success);
	}
    console.log("DB: Open");
}
function transaction_success() {
	dbCreated = true;
    db.transaction(check_devicehistory, transaction_error);
    db.transaction(get_appinfo, transaction_error);
    db.transaction(insert_appinfo, transaction_error);
}
function transaction_error(tx, error) {
	console.log("Database Error: " + error);
    console.log("Error: " + tx.message);
}
function transaction_null_handler(tx, results){
}

function get_appinfo(tx){
    var sql = "SELECT id, hits, timestamp " +
    "FROM gen_info";
    tx.executeSql(sql, [], getappdbinfo);
}
function getappdbinfo(tx, results) {
    var len = results.rows.length;
    if (len>0){
        hits = results.rows.item(0).hits + 1;
        timestamp = results.rows.item(0).timestamp;
        console.log("Hits: " + hits);
        var d = new Date();
        d.setTime(timestamp);
        console.log("App last loaded on: " + jQuery.timeago(d));
    }
}

function insert_appinfo(tx){
    var sql = "UPDATE gen_info SET "+
    "hits='"+hits+"', "+
    "timestamp='"+new Date().getTime()+"' " +
    "WHERE id = 1";
    tx.executeSql(sql);
}

function check_devicehistory(tx){
    var sql = "SELECT id " +
    "FROM device_history";
    tx.executeSql(sql, [], show_historylabel);
}
function show_historylabel(tx, results) {
    var len = results.rows.length;
    if (len>0){
        console.log("DB: History contains "+len+" devices");
    }
}

function get_devices(tx) {
    var sql = "SELECT id, devid, datetime, devimage, devname, devreldate " +
    "FROM device_history " +
    "GROUP BY devid " +
    "ORDER BY datetime " +
    "DESC LIMIT 10";
	tx.executeSql(sql, [], get_devices_success);
}
function get_devices_success(tx, results) {
    var lastdevice = -1;
    var len = results.rows.length;
    var html = '';
    var x=0;
    
	$('#devicelist li').remove();
	
    $('#devicelistheader').html('Showing '+results.rows.length+' recently viewed devices');
    
    for (var i=0; i<len; i++) {
        var device = results.rows.item(i);
        
        var phonename = device.devname;
        var phoneimage = '<img src="http://icons.thephonedatabase.com/tpd/'+device.devimage+'.png" class="list-icon"/>';
        var phonereldate = device.devreldate;
        var d = new Date();
        d.setTime(device.datetime);
        
        //var subtext = 'Viewed on ' + d.toDateString() + ' ' +d.toTimeString();
        var subtext = 'Viewed ' + jQuery.timeago(d);
        
        $('#devicelist').append('<li><a href="#devspecpage?did='+device.devid+'" id="'+device.devid+'" onclick="deviceid='+device.devid+';loadspecs();toggleTransition(\'#devicespage\', \'#specpage\', 17, 1);"><div class="left">'+phoneimage+'</div><div class="right"><h2>'+phonename+'</h2><p>'+subtext+'</p><span class="ui-li-count lidate">'+phonereldate+'</span></div></a></li>');
        
        x++;
    }
 
    setTimeout(function () {
        myScroll1.refresh();
        myScroll1.scrollTo(0, myScroll1.maxScrollY, 0);
        myScroll1.scrollTo(0, 0, 1500);
    }, 0);
    console.log("DB: Showing "+i+" devices");
}
function populateDB(tx) {
    //tx.executeSql('DROP TABLE IF EXISTS device_history');
    //tx.executeSql('DROP TABLE IF EXISTS device_favorite');
    //tx.executeSql('DROP TABLE IF EXISTS gen_info');
	var sql =
    "CREATE TABLE IF NOT EXISTS device_history ( "+
    "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
    "devid INTEGER, " +
    "datetime DATETIME, " +
    "devimage VARCHAR(50), " +
    "devname VARCHAR(50), " +
    "devreldate VARCHAR(50))";
    try{
        tx.executeSql(sql);
        console.log("DB: Created device_history TABLE");
    } catch (err){
        console.log(err);
    }
    sql =
    "CREATE TABLE IF NOT EXISTS device_favorite ( "+
    "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
    "devid INTEGER, " +
    "datetime DATETIME, " +
    "label VARCHAR(50), " +
    "devimage VARCHAR(50), " +
    "devname VARCHAR(50), " +
    "devreldate VARCHAR(50))";
    try{
        tx.executeSql(sql);
        console.log("DB: Created device_favorite TABLE");
    } catch (err){
        console.log(err);
    }
    sql =
    "CREATE TABLE IF NOT EXISTS gen_info ( "+
    "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
    "hits INTEGER, " +
    "timestamp DATETIME)";
    try{
        tx.executeSql(sql);
        tx.executeSql('INSERT INTO gen_info (hits, timestamp) VALUES (1, '+new Date().getTime()+')');
        console.log("DB: Created gen_info TABLE");
    } catch (err){
        console.log(err);
    }

}
function addToDeviceHistory(deviceid){
    try{
        console.log("Inserting...");
        if (dbCreated){
            db.transaction(insert_device, transaction_error);
            console.log("Inserted: " + deviceid);
        } else{
            console.log("DB does not exist");
        }
    } catch (err){
        console.log("INSERT ERROR: " + err);
    }
}

function insert_device(tx) {
    var sql = "INSERT INTO device_history (devid, datetime, devimage, devname, devreldate) VALUES ("+
    "'"+deviceid+"', "+
    "'"+new Date().getTime()+"', "+
    "'"+cdevimage+"', "+
    "'"+cdevname+"', "+
    "'"+cdevreldate+"' "+
    ")";
    tx.executeSql(sql);
}
 */

/*CALL ON PAGE REQUEST*/
function setDefaults(){
    
        FastClick.attach(document.body);
        
        setTimeout(function () {
               init_iScroll();
        }, 100);
    
    
        $('#slink').click(function(){
            var input = this;
            input.focus();
            input.setSelectionRange(0,999);
        });
    
    
    var element = document.getElementById('devicespage');
    var hammertime1 = Hammer(element).on("swiperight", function(event) {
        toggleTransition('#devicespage', '#menupage', 24, 0);
    });
    
    element = document.getElementById('brandpage');
    var hammertime2 = Hammer(element).on("swiperight", function(event) {
        toggleTransition('#brandpage', '#menupage', 24, 0);
    });
    element = document.getElementById('searchpage');
    var hammertime3 = Hammer(element).on("swiperight", function(event) {
        toggleTransition('#searchpage', '#menupage', 52, 0);
    });
    element = document.getElementById('specpage');
    var hammertime4 = Hammer(element).on("swiperight", function(event) {
        toggleTransition('#specpage', '#devicespage', 24, 0);
    });
    element = document.getElementById('comparepage');
    var hammertime5 = Hammer(element).on("swiperight", function(event) {
        toggleTransition('#comparepage', '#menupage', 24, 0);
    });
    element = document.getElementById('randomcomparepage');
    var hammertime5 = Hammer(element).on("swiperight", function(event) {
        toggleTransition('#randomcomparepage', '#menupage', 24, 0);
    });
    /*
    element = document.getElementById('gallerypage');
    var hammertime6 = Hammer(element).on("swiperight", function(event) {
        toggleTransition('#gallerypage', '#specpage', 17, 0);
        clearGallery();
    });
     */
}

function init_iScroll(){
    myScroll1 = new iScroll('wrapper1');
    myScroll2 = new iScroll('wrapper2');
    myScroll3 = new iScroll('wrapper3');
    myScroll4 = new iScroll('wrapper4');
    myScroll5 = new iScroll('wrapper5');
    myScroll6 = new iScroll('wrapper6');
    //myScrollD1 = new iScroll('wrapperD1');
    
    document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
    
    /* * * * * * * *
     *
     * Use this for high compatibility (iDevice + Android)
     *
     */
    document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);
    /*
     * * * * * * * */
    
    
    /* * * * * * * *
     *
     * Use this for iDevice only
     *
     */
    //document.addEventListener('DOMContentLoaded', loaded, false);
    /*
     * * * * * * * */
    
    
    /* * * * * * * *
     *
     * Use this if nothing else works
     *
     */
    //window.addEventListener('load', setTimeout(function () { loaded(); }, 200), false);
    /*
     * * * * * * * */

}

function hasinternet(){
    if (navigator.network.connection.type == Connection.NONE){
        //alert('The Phone Database requires an internet connection...');
        return false;
    };
    return true;
}

function onSearch(str){
    var searching = null;
    if (str.length >= 3){
    
        
        if (searching) {
            clearTimeout(searching);
        }
        
        // Start new time out
        searching = setTimeout(function() {
                               var $ul = $( '#searchresults' );
                               value = str,
                               html = "";
                               $ul.html( "" );
                               handleSearch($ul, value, html);
                               }, 1000);
    }
}

function handleSearch($ul, value, html){
    var s = value;
    s = s.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    console.log('S-' + s + '-S');
    var count = 0;
    if ( value && value.length > 2 ) {
        $.ajax({
                beforeSend: function() { $('#searchheader').html('Searching...'); }, //Show spinner
               url: searchfeed,
               dataType: 'json',
               type: 'GET',
               crossDomain: true,
               data: {
                    q: s
               }
       })
       .then( function ( data ) {
              $.each( data.query.results.item, function ( i, element ) {
                     var phoneimage = "";
                     
                     if (element.phoneImage.length > 0)
                     phoneimage = '<img src="' + element.phoneImage + '" class="list-icon"/>';
                     
                     var subtext = "";
                     if ((element.screenSize != "undefined") && (element.screenType != "undefined"))
                     subtext = element.screenSize+'" '+element.screenType;
                     
                     html += '<li><a href="#devspecpage?did='+element.phoneId+'" id="'+element.phoneId+'" onclick="deviceid='+element.phoneId+';loadspecs();toggleTransition(\'#searchpage\', \'#specpage\', 17, 1);"><div class="left">'+phoneimage+'</div><div class="right"><h2>'+element.phoneName+'</h2><p>'+subtext+'</p><span class="ui-li-count lidate">'+element.available+'</span></a></div></li>';
                     count++;
                     
                     });
                $('#searchheader').html('Showing ' + count + ' results for ' + s);
                $ul.html( html );
             
                setTimeout(function () {
                        myScroll3.refresh();
                        myScroll3.scrollTo(0, 0, 0);
                }, 0);
             
              });
    }
}
		
function loadbrands(){
	var gurl = brandsfeed;
    
    
    $.ajax({
           
           beforeSend: function() { $('#brandheader').html('Loading...'); }, //Show spinner
           //complete: function() {  }, //Hide spinner
           url:gurl,
           dataType: 'json',
           type: 'GET',
		   crossDomain: true,
           success:function(data){
			   $.each(data.query.results.item, function(i,element){
					  objBRAND[i] = {};
					  objBRAND[i]["brandname"] = element.brandName;
					  objBRAND[i]["brandurl"] = element.brandUrl;
					  objBRAND[i]["brandimage"] = element.brandImage;
					  objBRAND[i]["rank"] = element.rank;
					  count = i+1;
                 });
           		displayBrandList();
           }, error:function(jqXHR, textStatus, errorThrown){
           		//alert("failed: " + jqXHR.responseText + " - "+ textStatus + " - " + errorThrown );
           	}
           })
    
	}
	
function displayBrandList(){
    var x=0;
	var limit = objBRAND.length;
    
	$('#brandlist li').remove();
    $('#brandheader').html('Showing '+limit+' brands');
    
    while (x < limit){
        abrand=objBRAND[x];
        var brandimage = "";
        if (abrand.brandimage.length > 0)
            brandimage = '<img src="' + abrand.brandimage + '" class="list-icon"/>';
        
        $('#brandlist').append('<li><a href="#devicelistpage" id="'+abrand.brandurl+'" onclick="selectedbrandurl=\''+abrand.brandurl+'\';selectedtype=2;loaddevices();toggleTransition(\'#brandpage\', \'#devicespage\', 17, 1);"><div class="left">'+brandimage+'</div><div class="right"><h2>'+abrand.brandname+'</h2></div></a></li>');
        x++;
    }
    
    setTimeout(function () {
        myScroll2.refresh();
    }, 0);
}

function loaddevices(){
	var gurl = newdevfeed;
	if (selectedtype == 0)
		gurl = newdevfeed;
	else if (selectedtype == 1)
		gurl = populardevfeed;
	else if (selectedtype == 2)
		gurl = searchfeed + "?q=" + selectedbrandurl;
	
    
	if (selectedtype < 3){
        
        //$.ajaxSetup({xhrFields: {mozSystem: true}});
        
        $.ajax({
               beforeSend: function() {
                $('#devicelistheader').html('Loading...');
                $('#devicelist li').remove();
               }, //Show loading/spinner
               /*
               complete: function() {  }, //Hide spinner
               */
               url:gurl,
               dataType: 'json',
               type: 'GET',
               crossDomain: true,
               success: function (data){
                    objDEVICE = [];
               
                   $.each(data.query.results.item, function(i,element){
                          objDEVICE[i] = {};
                          objDEVICE[i]["phoneid"] = element.phoneId;
                          objDEVICE[i]["phonename"] = element.phoneName;
                          objDEVICE[i]["phoneurl"] = element.phoneUrl;
                          objDEVICE[i]["phoneimage"] = element.phoneImage;
                          objDEVICE[i]["screensize"] = element.screenSize;
                          objDEVICE[i]["screentype"] =element.screenType;
                          objDEVICE[i]["available"] = element.available;
                          objDEVICE[i]["talktime"] = element.talktime;
                          count = i+1;
                     });
               
                    displayDeviceList();
                }, error:function(jqXHR, textStatus, errorThrown){
                    alert("failed: " + jqXHR.responseText + " - "+ textStatus + " - " + errorThrown );
                }
            });
        }
    
    if (selectedtype == 3){
        //loadhistory();
    }
    
}

/*
function loadhistory(){
    db.transaction(get_devices, transaction_error);
}
 */

function displayDeviceList(){
    var x=0;
	var limit = objDEVICE.length;
    
    var stext = "newest";
	if (selectedtype == 1)
		stext = "popular";
    
    $('#devicelistheader').html('Showing '+limit+' ' +stext+ ' devices');
    
    while (x < limit){
        adevice=objDEVICE[x];
        
        var phoneimage = "";
        if (adevice.phoneimage.length > 0)
            phoneimage = '<img src="' + adevice.phoneimage + '" class="list-icon"/>';
        
		var subtext = "";
		if ((adevice.screensize != "undefined") && (adevice.screentype != "undefined"))
			subtext = adevice.screensize+'" '+adevice.screentype;
		
        $('#devicelist').append('<li><a href="#devspecpage?did='+adevice.phoneid+'" id="'+adevice.phoneid+'" onclick="deviceid='+adevice.phoneid+';loadspecs();toggleTransition(\'#devicespage\', \'#specpage\', 17, 1);"><div class="left">'+phoneimage+'</div><div class="right"><h2>'+adevice.phonename+'</h2><p>'+subtext+'</p><span class="ui-li-count lidate">'+adevice.available+'</span></div></a></li>');
        
        x++;
    }
    
    setTimeout(function () {
        myScroll1.refresh();
        myScroll1.scrollTo(0, myScroll1.maxScrollY, 0);
        myScroll1.scrollTo(0, 0, 1500);
    }, 0);
}

function loadrandomcomparisons(){
	var gurl = randomcomparefeed;
	var html = "";
	
    $.ajax({
           
           beforeSend: function() {
                animateIcon('refreshcomparepage', 1, 1);
                $('#randomcompareheader').html('Loading some randomness...');
           }, //Show spinner
           complete: function() {
                animateIcon('refreshcomparepage', 1, 0);
           }, //Hide spinner
           url:gurl,
           dataType: 'json',
           type: 'GET',
		   crossDomain: true,
           success:function(data){
           
           var count=0;
            $('#randomcompare').empty();
           
            $.each(data.query.results.item, function(i,element){
                html += '<li class="comparerow"><a href="#comparisonpage" onclick="comparetwo('+element.phoneId1+', '+element.phoneId2+', '+element.phoneImageId1+', '+element.phoneImageId2+');loadcomparison();toggleTransition(\'#randomcomparepage\', \'#comparepage\', 17, 1);"><div class="left device"><img itemprop="image" src="http://icons.thephonedatabase.com/tpd/'+element.phoneImageId1+'.png" alt="Front View" style="opacity: 1;"><div class="dname">'+element.phoneName1+'</div></div><div class="right device"><img itemprop="image" src="http://images.thephonedatabase.com/tpd/medium/'+element.phoneImageId2+'.png" alt="Front View" style="opacity: 1;"><div class="dname">'+element.phoneName2+'</div></div><div class="text"><div class="vs"><span class="score">'+element.phoneScore1+'%</span>&nbsp;<span class="inner">vs</span>&nbsp;<span class="score">'+element.phoneScore2+'%</span></div></div></a></li>';
                   count++;
            });
           
           //html = '<li data-role="list-divider" role="heading" class="ui-li ui-li-divider ui-bar-b">Random Comparisons</li>'+html;
           
           $('#randomcompare').append(html);
           $('#randomcompareheader').html('Showing '+count+' random comparisons');
           
           setTimeout(function () {
                    myScroll6.refresh();
            }, 0);

        }
    });
}

function loadspecs(){
	var gurl = specfeed + "?id=" + deviceid;
	var html = "";
	var shtml = "";
	var manufacturer = "";
	var model = "";
	var pimage = "";
	var fimageid = "";
    var availability = "";
	var width = "";
	var height = "";
	var depth = "";
	var weight = "";
    var colors = "";
	var icount = 0;
	var count = 0;
	
        /*
    console.log('1 - start');

    
    var xhr = new XMLHttpRequest({mozSystem: true});
    console.log('2 - request');
    xhr.open("GET", gurl, true);
    console.log('3 - fetch');
    xhr.onreadystatechange = function() {
        console.log('4 - state change');
        if (xhr.readyState == 4) {
            console.log('5 - ready');
            
            obj = JSON.parse(xhr.responseText);
            
            console.log('6 - parsed');
            result = "Fetched: " + obj + ""; // obj.something
            console.log(result);
        }
    }
    xhr.send();
    */
    
    
	$.ajax({
           
           beforeSend: function() {
                $('#specheader').html('Loading specs...');
                $('#specsmimage').html('');
                $('#specsummary').html('');
                $('#specifications li').remove();
           }, //Show spinner
           url:gurl,
           dataType: 'json',
           type: 'GET',
           crossDomain: true,
           success:function(data){
           
                objDEVGALLERY = [];
           
				$.each(data.query.results.item, function(i,element){ // should return only 1 item
					
					$.each(element, function(index,value){
						if ((index != 'Device') && 
							(index != 'Size and Weight') &&
							(index != 'Images'))
							html += '<li class="divider">'+index+'</li>';
						
						$.each(value, function(indexi,valuei){
							if (index == 'Images'){
                                if (indexi == 'Front'){
                                    fimageid = valuei;
									pimage = '<div class="inner"><a href="#gallerypage" onclick="loadallgallery();toggleTransition(\'#specpage\', \'#gallerypage\', 1, 1);"><img src="http://images.thephonedatabase.com/tpd/medium/'+valuei+'.png"></a></div>';
                                }
                                if (indexi != 'Video'){
									objDEVGALLERY[icount] = valuei;
									icount++;
								}
							} else if (index == 'Device'){
								if (indexi == 'Model')
									model = valuei;
								else if (indexi == 'Manufacturer')
									manufacturer = valuei;
								else
									shtml += ' ' + valuei;
							} else if (index == 'Size and Weight'){
								if (indexi == 'Depth')
									depth = valuei;
								else if (indexi == 'Width')
									width = valuei;
								else if (indexi == 'Height')
									height = valuei;
								else if (indexi == 'Weight')
									weight = valuei;
								else
									shtml += ' ' + valuei;
							//} else if (index == 'Casing'){
                            //   if (indexi == 'Color')
                            //    colors += valuei + ' ';
                            } else{
                               html += '<li><h5 class="etitle">'+indexi+'</h5><h6>'+valuei+'</h6></li>';
                               if (indexi == 'Released on')
                                    availability = valuei;
							}
						});
						
					});
					
					count = i+1;
                 });
           
                //if (colors.length>0){
                //    html += '<li data-role="list-divider" role="heading" class="ui-li ui-li-divider ui-bar-b">Casing</li><li><h2 class="etitle">Colors</h2><p>'+colors+'</p></li>';
                //}
           
                $('#specheader').html(manufacturer + ' ' + model + ' specs');
           
                $('#specsmimage').html(pimage);
                $('#specsummary').html('<h2>' + manufacturer + ' ' + model + '</h2><h3>' + weight + '</h3><h4>' + width + ' x ' + height + ' x '  + depth + '<p><a href="#comparepanel" class="btn compare" onclick="addtocompare(\''+deviceid+'\', \''+fimageid+'\');showPrompt(\'#compareprompt\');" >Compare</a></p></h4>');
           
                sharelink = 'http://tpdb.net/'+manufacturer.replace(" ", "_")+'_'+model.replace(" ","_")+'_'+deviceid+'_Cell_Phone';
                sharelink = sharelink.replace(" ", "_");
                sharelink = encodeURI(sharelink);
                sharetitle = manufacturer + ' ' + model;
           
                $('#specifications').html(html);
           
                cdevimage = fimageid;
                cdevname = manufacturer + ' ' + model;
                cdevreldate = availability;
                //addToDeviceHistory(deviceid);
           
                setTimeout(function () {
                        myScroll4.refresh();
                        myScroll4.scrollTo(0, myScroll4.maxScrollY, 0);
                        myScroll4.scrollTo(0, 0, 1500);
                }, 0);
           }, error:function(jqXHR, textStatus, errorThrown){
           		//alert("failed: " + jqXHR.responseText + " - "+ textStatus + " - " + errorThrown );
				//alert("failed: "+ textStatus + " - " + errorThrown );
			}
           })
    
	
	}

function comparetwo(deviceid1, deviceid2, fimageid1, fimageid2){
    objCOMPARE = [];
    addtocompare(deviceid1, fimageid1);
    addtocompare(deviceid2, fimageid2);
}

function addtocompare(deviceid, fimageid){
    var image = '<img src="http://images.thephonedatabase.com/tpd/medium/'+fimageid+'.png">';
    var csize = objCOMPARE.length;
    if (csize < 2){
        if (incompare(deviceid) == false){
            objCOMPARE[csize] = {};
            objCOMPARE[csize]["did"] = deviceid;
            objCOMPARE[csize]["image"] = image;
            refreshcomparedevices();
        }
    }
}

function removefromcompare(key){
    objCOMPARE.splice(key,1);
    refreshcomparedevices();
}

function incompare(deviceid){
    for (var x=0,csize=objCOMPARE.length;x<csize;x++){
        if (objCOMPARE[x]["did"]==deviceid)
            return true;
    }
    return false;
}

function refreshcomparedevices(){
    console.log('refreshing');
    
    var csize = objCOMPARE.length;
    var html = '';
    $('#devcontainer').empty();
    
    for (var x=0;x<csize;x++){
        html = '<li class="device">'+objCOMPARE[x]["image"]+'<a href="#" onclick="removefromcompare('+x+')" class="remove">Remove</a></li>';
        $('#devcontainer').append(html);
    }
    
    if (csize <= 1){
        //$('#comparedialogheader').html('Select one more device to compare...');
    }
    
    if (csize > 1){ // show compare button at the end
        //$('#comparedialogheader').html('Ready to compare');
        html = '<a href="#comparisonpage" onclick="loadcomparison();hidePrompt(\'#compareprompt\');toggleTransition(\'#specpage\', \'#comparepage\', 17, 1);"><div class="btn action">Compare</div></a>';
        $('#devcontainer').append(html);
    } else if (csize <= 0){
        hidePrompt('#compareprompt');return false;
    }
}

function loadcomparison(){
    
    var gurl = comparefeed + '?devids=';
    for (var x=0, cdevices=objCOMPARE.length;x<cdevices;x++){
        if (x>0)
            gurl += '_vs_';
        gurl += objCOMPARE[x]["did"];
        
    }
    
    console.log("Comparing: " + objCOMPARE[0]["did"] + " vs " + objCOMPARE[1]["did"]);
    
    if (cdevices>1){
        
        $.ajax({
               beforeSend: function() {
                    $('#compareheader').html('Loading comparison...');
                    $('#comparetable').empty();
               }, // Show loading
               /*
               complete: function() {  }, //Hide spinner
               */
               url:gurl,
               dataType: 'json',
               type: 'GET',
               crossDomain: true,
               success:function(data){
               ecount = 0;
               var objCOMPAREIT = [];
               
                $.each(data.query.results.item, function(i,element){ // should return only 1 item
                      //console.log(i + ' - ' + element);
                      rcount = 0;
                      $.each(element, function(cat,value){
                             //console.log(cat + ' - ' + value);
                             //objCOMPAREIT[rcount] = [];
                             //objCOMPAREIT[rcount][ecount] += '<tr>'+value+'</tr>';
                             
                             $.each(value, function(subcat,valuei){
                                    //console.log(cat + ' - ' + subcat + ' - ' + valuei);
                                    
                                    if (valuei.toLowerCase() == 'yes')
                                        valuei = 'YES';
                                    else if (valuei.toLowerCase() == 'no')
                                        valuei = 'NO';
                                    
                                    if (rcount >= 14){
                                        if (ecount==0){
                                            objCOMPAREIT[rcount] = [];
                                            objCOMPAREIT[rcount][ecount] = '<tr><th class="label">'+subcat+'</th><td>'+valuei+'</td>';
                                        }else{
                                            objCOMPAREIT[rcount][ecount] = '<td class="ui-table-priority-1 ui-table-cell-visible">'+valuei+'</td></tr>';
                                        }
                                    } else{
                                        if (ecount==0)
                                            objCOMPAREIT[rcount] = [];
                                        objCOMPAREIT[rcount][ecount] = valuei;
                                    }
                                    //console.log(rcount + '-' + ecount + ' - ' + objCOMPAREIT[rcount][ecount]);
                                    rcount++;
                            });
                        });
                       ecount++;
                });
               
               output = '';
               for (var x=14;x<rcount-4;x++){
                for (var y=0; y<ecount;y++){
                    output += objCOMPAREIT[x][y];
                    //console.log(x + '-' + y + ' = '+ objCOMPAREIT[x][y]);
                }
               }
               
                // output
                html = '';
                html += '<table data-role="table" id="phone-table" class="phone-compare ui-shadow table-stroke ui-table ui-table-columntoggle"><thead>';
               
                html += '<tr id="comparescroll"><th class="label">Model</th><th><a href="#devspecpage?did='+objCOMPAREIT[11][0]+'" id="cl'+objCOMPAREIT[11][0]+'" onclick="deviceid='+objCOMPAREIT[11][0]+';loadspecs();toggleTransition(\'#comparepage\', \'#specpage\', 17, 1);"><h4>'+objCOMPAREIT[10][0]+'</h4><h3>'+objCOMPAREIT[9][0]+'</h3></a></th><th data-priority="1" class="ui-table-priority-1 ui-table-cell-visible"><a href="#devspecpage?did='+objCOMPAREIT[11][1]+'" id="cl'+objCOMPAREIT[11][1]+'" onclick="deviceid='+objCOMPAREIT[11][1]+';loadspecs();toggleTransition(\'#comparepage\', \'#specpage\', 17, 1);"><h4>'+objCOMPAREIT[10][1]+'</h4><h3>'+objCOMPAREIT[9][1]+'</h3></th></tr></a></thead>';
                html += '<tbody>';
                html += '<tr class="photos"><th class="label">Image</th><td><a href="#img-iphone5" class="ui-link" onclick="deviceid='+objCOMPAREIT[11][0]+';loadspecs();toggleTransition(\'#comparepage\', \'#specpage\', 17, 1);"><img src="http://icons.thephonedatabase.com/tpd/'+objCOMPAREIT[13][0]+'.png"></a></td><td class="ui-table-priority-1 ui-table-cell-visible"><a href="#img-galaxy" class="ui-link" onclick="deviceid='+objCOMPAREIT[11][1]+';loadspecs();toggleTransition(\'#comparepage\', \'#specpage\', 17, 1);"><img src="http://icons.thephonedatabase.com/tpd/'+objCOMPAREIT[13][1]+'.png"></a></td></tr>';
                html += '<tr><th class="label">Score</th><td><div class="chart"><div class="percentage" data-percent="'+objCOMPAREIT[0][0]+'"><span>'+objCOMPAREIT[0][0]+'</span>%</div></div></td>';
                html += '<td><div class="chart"><div class="percentage" data-percent="'+objCOMPAREIT[0][1]+'"><span>'+objCOMPAREIT[0][1]+'</span>%</div></div></td></tr>';
                html+= output;
               
                html += objCOMPAREIT[rcount-1][0]+objCOMPAREIT[rcount-1][1]; // Width
                html += objCOMPAREIT[rcount-3][0]+objCOMPAREIT[rcount-3][1]; // Height
                html += objCOMPAREIT[rcount-4][0]+objCOMPAREIT[rcount-4][1]; // Depth
                html += objCOMPAREIT[rcount-2][0]+objCOMPAREIT[rcount-2][1]; // Weight
                html += '</tbody></table>';
                
                //console.log(html);
               
                $('#comparetable').append(html);
                $('#compareheader').html(objCOMPAREIT[9][0]+' vs '+objCOMPAREIT[9][1]);
               
                $('.percentage').easyPieChart({
                    barColor: function(percent) {
                    percent /= 100;
                    return "rgb(" + Math.round(255 * (1-percent)) + ", " + Math.round(255 * percent) + ", 0)";
                    },
                    trackColor: 'rgba(0, 0, 0, 0.05)',
                    scaleColor: false,
                    lineCap: 'butt',
                    lineWidth: 20,
                    sie:110,
                    animate: 1000
                    });
               
                sharelink = 'http://tpdb.net/'+objCOMPAREIT[10][0].replace(" ", "_")+'_'+objCOMPAREIT[9][0].replace(" ", "_")+'_'+objCOMPARE[0]["did"]+'_vs_'+objCOMPAREIT[10][1].replace(" ", "_")+'_'+objCOMPAREIT[9][1].replace(" ", "_")+'_'+objCOMPARE[1]["did"]+'_Compare_Phones';
                sharelink = sharelink.replace(" ", "_");
                sharelink = encodeURI(sharelink);
                sharetitle = objCOMPAREIT[10][0]+' '+objCOMPAREIT[9][0]+' vs '+objCOMPAREIT[10][1]+' '+objCOMPAREIT[9][1];
               
                    setTimeout(function () {
                               myScroll5.refresh();
                               myScroll5.scrollTo(0, 0, 0);
                          }, 0);
               
               }, error:function(jqXHR, textStatus, errorThrown){}})
    
    }
}

function loadallgallery(){
    setTimeout(function () {
        var gsize = objDEVGALLERY.length;
        var gimages = '';
        
        $('#gallery').html('');
        $('#galleryheader').html('Loading image...');
        
        if (gsize > 0){
            for (var i=0;i<gsize;i++)
                gimages += '<div><img src="http://images.thephonedatabase.com/tpd/large/'+objDEVGALLERY[i]+'.jpg" alt="'+objDEVGALLERY[i]+'" /></div>';
        }
        $('#gallery').html(gimages);
        $('#galleryheader').html('Gallery');
        
        window.mySwipe = Swipe(document.getElementById('slider'));
    }, 100);
}

function clearGallery(){
    $('#gallery').html('');
}

function loadgallery(){
	var gsize = objDEVGALLERY.length;
	var gimage = '';
	
	$('#gallery').html('');
    $('#galleryheader').html('Loading image...');
    
	if (gsize > 0){
		selectedimage = 0;
		gimage = '<a href="#" onclick="loadimage(1);"><img src="http://images.thephonedatabase.com/tpd/large/'+objDEVGALLERY[selectedimage]+'.jpg" alt="'+objDEVGALLERY[selectedimage]+'" /></a>';
	}
	$('#gallery').html(gimage);
    $('#galleryheader').html('Gallery');
}

function loadimage(direction){
	var gsize = objDEVGALLERY.length;
	var gimage = '';
    
    $('#galleryheader').html('Loading image...');
	$('#gallery').html('');
	
	if (direction == 0){ // previous
		selectedimage--;	
	} else if (direction == 1){// next
		selectedimage++;
	}
	
	if (gsize > 0){
		if (selectedimage >= gsize)
			selectedimage = 0;
		if (selectedimage < 0)
			selectedimage = gsize;
			
		gimage = '<a href="#" onclick="loadimage(1);"><img src="http://images.thephonedatabase.com/tpd/large/'+objDEVGALLERY[selectedimage]+'.jpg" alt="'+objDEVGALLERY[selectedimage]+'" /></a>';
		
	}
	
	$('#gallery').html(gimage);
    $('#galleryheader').html('Gallery');
}

function loadsharedialog(){
    document.getElementById("slink").value= sharelink;
    /*
    setTimeout(function () {
               myScrollD1.refresh();
    }, 0);
     */
}

function copylink(){
    Copied = sharelink.createTextRange();
    Copied.execCommand("Copy");
    $('.ui-dialog').dialog('close');
}
function emaillink(){
    window.location.href = 'mailto:?subject='+sharetitle+' from The Phone Database&body=Hey I think you will find the '+sharetitle+' information interesting, here are the details: '+sharelink+'%0A%0A%0A©ThePhoneDatabase - www.thephonedatabase.com';
    //$('.ui-dialog').dialog('close');
}
function tweetlink(){
    //window.location.href = 'http://twitter.com/home?status='+sharetitle+' '+sharelink;
    var twitterpost = sharetitle+' '+sharelink;
    twitterpost = encodeURI(twitterpost);
    window.open('http://twitter.com/home?status='+twitterpost, '_blank');
    //window.location.href = 'http://twitter.com/home?status='+twitterpost;
    
    //console.log(sharelink);
}
function facebooklink(){
    //console.log(sharelink);
    window.open('http://www.facebook.com/share.php?u='+sharelink, '_blank'); // _blank inapp or _system to open in browser (might be a better option if app installed)
    //window.location.href = 'http://www.facebook.com/share.php?u='+sharelink;
    //console.log(sharelink);
}


(function mobileSafariFormsAssistantHack($) {
 "use strict";
 $(document).bind("pageinit",
                  function installDelegation(pageEvent) {
                  var $page = $(pageEvent.target);
                  $page.delegate("input,textarea,select", "blur",
                                 function onBlur(inputEvent) {
                                 setTimeout(function onAllBlurred() {  // Need this timeout for .ui-focus to clear
                                            // Are all of the input elements on the page blurred (not focused)?
                                            if ($page.find("input.ui-focus,textarea.ui-focus,select.ui-focus").length === 0) {
                                            $.mobile.silentScroll(0);        // If so, scroll to top
                                            }
                                            },
                                            0);
                                 });
                  });
 }(jQuery));

$(document).bind("mobileinit", function() {
                 $.mobile.defaultPageTransition = "slide";
                 });




