[Sony Ericsson Xperia Mini, Mini Pro, Xperia Pro, A] SigitCGumilars:
Sript Code For Messeges Port

var mj;
var recipientPin;
var showingMessages = false;
var curContactID = 0;

function Pressed(event) {
if (event.keyCode == 13) {
SendMessage();
return true;
}
}

function RemoveContactMessages(ContactIDxx) {
var messagesJson = localStorage.getItem("messagesJson"); //get the messages json from storage
if (messagesJson == null || messagesJson == undefined) { return; } //if there is none just return, they aiont done any messages

if (messagesJson != null & messagesJson != "") {

messagesJson = JSON.parse(messagesJson); //convert the stored json string in to a json array

var iRemove = -1;
$.each(messagesJson, function (iContactPhone, contactPhone) //loop each contact on the phone
{
if (contactPhone.ContactID == ContactIDxx) {
iRemove = iContactPhone;
}
});

messagesJson.splice(iRemove, 1);
//now we sort the messagesjson by the lastmessageid desc
messagesjson = messagesJson.sort(function (a, b) { return a.LastMessageID < b.LastMessageID });

console.log(messagesjson);

//Store the messages on the phone storage
var con = JSON.stringify(messagesJson)

localStorage.setItem("messagesJson", con);

}

}

function syncMessages(refresh) {
//localStorage.removeItem("messagesJson");
//return;
var doRefresh = false;
logLaunch();

var yyy = localStorage.getItem("UserID");
if (yyy == null) { return; }

var messagesJson = localStorage.getItem("messagesJson"); //get the messages json from storage
if (messagesJson == null || messagesJson == undefined) { messagesJson = ""; } //if there is none set it to empty string

var BaseID = 0;

if (messagesJson != null & messagesJson != "") {
//they have stored messages
messagesJson = JSON.parse(messagesJson); //convert the stored json string in to a json array

//set the baseid to the last message received which is the first contactmessage object and the last messageid in it
var y = messagesJson[0];
BaseID = y.Messages[y.Messages.length - 1].MessageID; //find the id of the message who is last in the array, base id is used to find messages who were added after this id, syncing!
}
console.log('base id: ' + BaseID);
$.ajax({
type: "POST",
url: HandlersFolder + "GetMessages.ashx",
contentType: "application/json; charset=utf-8",
data: { "UserIDx": localStorage.getItem("UserID"), "BaseID": BaseID },
dataType: "jsonp",
success: function (data) {
console.log(localStorage.getItem("UserID"));
var json;
if (data != "[]") { //this means new messages are found on the db, like if it does not equal []
console.log("New messages being returned");
//console.log(data);
json = JSON.parse(data);

if (messagesJson == null || messagesJson == "") {
messagesJson = json;
//This means they have no messages on the phone so we set the messages on the phone to the contacts from the db
console.log('got no messages on phone');
doRefresh = true;
}
else {
//they do have messages on the phone, merge them with the messages we got from the db

console.log('attempting merge...');
$.each(json, function (iContactServer, contactServer) //loop each contact from the server
{
var foundContact = false; //bool so we know if this contact already exists on this phone
$.each(messagesJson, function (iContactPhone, contactPhone) //loop each contact on the phone
{
if (contactServer.ContactName == contactPhone.ContactName) {
//We have a match
foundContact = true;
//start by setting the lastmessageid
contactPhone.LastMessageID = contactServer.LastMessageID;
$.each(contactServer.Messages, function (iServerMessage, ServerMessage) //loop each message returned from the server for this contact
{
//console.log(ServerMessage);
var foundMessageMatch = false;
$.each(contactPhone.Messages, function (iPhoneMessage, PhoneMessage) //loop each message on the phone for this contact
{
//console.log(PhoneMessage);
if (PhoneMessage.MessageID == ServerMessage.MessageID) { foundMessageMatch = true; } //check to see if we have this message on the phone already
});

if (foundMessageMatch == false) {
//the message isnt on the phone yet
doRefresh = true;
console.log('adding message');
messagesJson[iContactPhone].Messages.push(ServerMessage);
}

});
}
});
if (foundContact == false) {
//oh no the contact doesnt already exist on this phone, we need to add it
//todo at a later date, need to add the new contact n that
}
});
}
}

//now we sort the messagesjson by the lastmessageid desc
console.log('mj = ' + messagesJson);
try {
messagesjson = messagesJson.sort(function (a, b) { return a.LastMessageID < b.LastMessageID });
} catch (err) { }

//Store the messages on the phone storage
var con = JSON.stringify(messagesJson)

localStorage.setItem("messagesJson", con);

if (refresh == false) {
console.log('loading messages cause we aint refreshing');
LoadMessages();
}
else {
if (doRefresh == true) {
console.log('loading messages cause we are refreshing and we have new messages');
LoadMessages();
}
}

},
//Failed, probably cause of connection
error: function () { showAlert("Oh No!", "Please check your connection"); }
});
}

function LoadMessages() {

$(lstMessages).empty();
try {
$(lstMessages).listview("refresh");
} catch (err) { }

var messagesJson = localStorage.getItem("messagesJson"); //get the messages json from storage

if (messagesJson == null) { return; }

messagesJson = JSON.parse(messagesJson);
mj = messagesJson;

$.each(messagesJson, function (index1, contact) {
//this is how to loop each contactmessage and refer to its properties
var x = contact.ContactName.replace(" ", "~#");

$(lstMessages).append("<li><a onclick=goToMessages('" + contact.ContactID + "','" + x + "');LoadContactMessages('"+ contact.ContactID +"');><h2>" + unescape(contact.ContactName) + " <br/>(" + unescape(contact.ContactPin) + ")</h2><p>" + unescape(contact.Messages[contact.Messages.length - 1].Message) + "</p><p class='ui-li-aside' style='margin-top:1.8em; margin-right:1em;'>" + contact.Messages[contact.Messages.length - 1].DateWhen2 + "</p></a></li>");

});
try {
$(lstMessages).listview("refresh");
} catch (err) { }

}

function goToMessages(ContactID, ContactName) {
ContactName = ContactName.replace("~#", " ");
viewingContactID = ContactID;
$.mobile.changePage("#messagePage", { transition: "slide" });
$('#headerMessagePage').html(unescape(ContactName));
}

var MessagesIDs = [];

function LoadContactMessages(ContactID)
{
MessagesIDs = [];
curContactID = ContactID;

$('#theMessages').html('');
$.each(mj, function (index1, contact) {
if (contact.ContactID == ContactID) {

//console.log(contact.Messages);
$.each(contact.Messages, function (index2, message) {
$('#theMessages').append("<div style='width:100%; float:left;'></div>");
if (message.Type == "Outgoing") {
$('#theMessages').append("<p class='triangle-isosceles yellowOne'><span class='yellowDate'>21/10/2012 13:23:11<br /></span>" + message.Message + "</p>");
recipientPin = message.RecipientPin;
}
else {
$('#theMessages').append("<p class='triangle-right blueOne'><span class='blueDate'>21/10/2012 13:23:11<br /></span>" + message.Message + "</p>");
recipientPin = message.SenderPin;
}
MessagesIDs.push(message.MessageID);
});

}

});

showingMessages = true;

//console.log(MessagesIDs);

setTimeout(function () {
$(document).scrollTop($(document).height());
}, 1500);
}

function RefreshContactMessages() {

if (curContactID == 0) { console.log('not set'); return;}

$.each(mj, function (index1, contact) {
if (contact.ContactID == curContactID) {

//console.log(contact.Messages);
$.each(contact.Messages, function (index2, message) {

if (MessagesIDs.indexOf(message.MessageID) == -1) {

$('#theMessages').append("<div style='width:100%; float:left;'></div>");
if (message.Type == "Outgoing") {
$('#theMessages').append("<p class='triangle-isosceles yellowOne'><span class='yellowDate'>21/10/2012 13:23:11<br /></span>" + message.Message + "</p>");
recipientPin = message.RecipientPin;
}
else {
$('#theMessages').append("<p class='triangle-right blueOne'><span class='blueDate'>21/10/2012 13:23:11<br /></span>" + message.Message + "</p>");
recipientPin = message.SenderPin;
}
MessagesIDs.push(message.MessageID);
setTimeout(function () {
console.log('scrolling');
$(document).scrollTop($(document).height());
}, 1500);
}
});

}

});

}

function SendMessage() {

var origHeight = $('#txtMessage').height();

//get the message they want to send
var msg1 = $('#txtMessage').val().replace('\n', '<br>');
var msg = escape($('#txtMessage').val().replace('\n', '<br>'));

//if no message then do one
if (msg == "") { return; }

var SenderUID = localStorage.getItem("UserID");
var SenderPin = localStorage.getItem("UserPin");

// console.log(SenderUID);
// console.log(SenderPin);
// console.log(recipientPin);
// return;

//Post it off to the server checking the account exists, it will return the users pin and userid as json if all ok or 'no' if its a fail
$.ajax({
type: "POST",
url: HandlersFolder + "SendMessage.ashx",
contentType: "application/json; charset=utf-8",
data: { "Message": msg, "SenderUID": escape(SenderUID), "SenderPin": escape(SenderPin), "RecipientPin": escape(recipientPin) },
dataType: "jsonp",
success: function (data) {
console.log('message sent')
$('#theMessages').append("<div style='width:100%; float:left;'></div>");
$('#theMessages').append("<p class='triangle-isosceles yellowOne'><span class='yellowDate'>21/10/2012 13:23:11<br /></span>" + msg1 + "</p>");
setTimeout(function () {
$(document).scrollTop($(document).height());
}, 1500);
$('#txtMessage').val('');

$('#txtMessage').height(35);

MessagesIDs.push(parseInt(data));

syncMessages(false);

},
//Failed, probably cause of connection
error: function () { showAlert("Oh No!", "Please check your connection"); }
});

}