(function($){
    var htmlDecode = function(text,urlEscape) {
        if (typeof text != "undefined") {
            if (typeof urlEscape == "undefined") {
                urlEscape = true;
            }
            
            // Facebook sucks so we do this manually
            if (typeof Facebook != "undefined" && Facebook.streamPublish != null) {
                if (text != null) {
                    text = text.replace("&nbsp;"," ");
                    text = text.replace("&quot;","\"");
                    text = text.replace("&amp;","&");
                    text = text.replace("&lt;","<");
                    text = text.replace("&gt;",">");
                }
            } else {
                text = $("<div></div>").html(text).text();
            }
        
            if (urlEscape) {
                return escape(text);
            }
            
        }
        
        return text;
    };
    
    // Platform Functions
    var facebookFeed = function(o,callback) {
         // Newsfeed
        var attachment = {
            'name' : htmlDecode(o.title,false),
            'description' : htmlDecode(o.description,false),
            'media':[]
        };
        
        // Add link to title if link exists
        if (o.titleUrl) { 
            attachment.href = o.titleUrl;
        } else if (o.linkUrl) {
            attachment.href = o.linkUrl;
        }
        
        // Add Images
        if (o.images && o.images.length > 0) {
            for (var i=0,len=o.images.length;i<len;i++) {
                o.images[i].type = "image";
            }
            attachment.media = o.images;
        }
        
        var actionLinks = null;
        if (o.linkText && o.linkUrl) {
            actionLinks = [{
                "text" : htmlDecode(o.linkText,false),
                "href" : o.linkUrl
            }];
        }
        
        // Check for remote api, facebook, fb connect, and if all else fails open a window
        var streamPublishFn = null;
        if (typeof Facebook != "undefined" && Facebook.streamPublish != null) {
            streamPublishFn = Facebook.streamPublish;
        } else if (typeof FB != "undefined" && typeof FB.Connect != "undefined" && FB.Connect.showFeedDialog != null) {
            streamPublishFn = FB.Connect.streamPublish;
        } else if ($.remote) { // Facebook Connect service in parent FRAME (aka page hosting our embed code)
            streamPublishFn = $.remote.streamPublish;
        } else {
            var shareLink = o.linkUrl;
            if (o.titleUrl) { 
                shareLink = o.titleUrl;
            }
            
            var facebookShareUrl = $.transponder.serverUrl()+"/transponder/share/facebook"+"?t=" + htmlDecode(o.title)+"&d=" + htmlDecode(o.description)+"&u=" + htmlDecode(shareLink)+"&cache="+(Math.random()+"").substring(2);
            
            // Add images if we have any
            if (o.images && o.images.length > 0) {
                facebookShareUrl += "&i=" + htmlDecode(o.images[0].src);
            }
            
            if (callback) {
               callback();
            }
            
            return openWindow("http://www.facebook.com/sharer.php?u="+escape(facebookShareUrl)+"&t="+htmlDecode(o.title), false, false, o.elem);
        }
        
        if (streamPublishFn) {
            streamPublishFn(htmlDecode(o.userText,false),attachment,actionLinks,o.targetId,htmlDecode(o.prompt,false), function(post_id) {
                if (post_id && post_id != 'null' && callback) {
                    callback();
                }
            });
        }
    };
    
    var myspaceFeed = function(o,callback) {
        var shareLink = o.linkUrl;
        if (o.titleUrl) { 
            shareLink = o.titleUrl;
        }
        
        var myspaceShareUrl = $.transponder.serverUrl()+"/transponder/share/myspace"+"?t=" + htmlDecode(o.title)+"&d=" + htmlDecode(o.description)+"&u=" + htmlDecode(shareLink)+"&cache="+(Math.random()+"").substring(2);
        
        // Add images if we have any
        if (o.images && o.images.length > 0) {
            myspaceShareUrl += "&i=" + htmlDecode(o.images[0].src);
        }
        
        var myspaceUrl = "http://www.myspace.com/Modules/PostTo/Pages/?u="+escape(myspaceShareUrl);
        
        var success = openWindow(myspaceUrl, false, false, o.elem);
        
        if (callback) {
            callback();
        }
        
        return success;
    };
    
    var twitterFeed = function(o,callback) {
        var twitterShareUrl = "http://twitter.com/home?status="+ htmlDecode(o.title);
        
        var success = openWindow(twitterShareUrl, true, false, o.elem);
        
        if (callback) {
            callback();
        }
        
        return success;
    };
    
    var email = function(o,callback) {
        var mailUrl = "mailto:"+o.emailTo+"?subject="+escape(o.emailSubject)+"&body="+escape(o.emailBody);
        var success = openWindow(mailUrl, false, true, o.elem);
       
        if (callback) {
            callback();
        }
        
        return sucess;
    }
    
    var nokiaSend = function(o,callback) {
        var html = "";
        if ($.currentPlatform() == "nokia") {
            var so = device.getServiceObject("Service.Contact", "IDataSource");
            var list = so.IDataSource.GetList({
                Type : "Contact"
            });
            var contacts = list.ReturnValue;
            // Valid keys for phone numbers in order of precidence
            var validFields = [
                'MobilePhoneGen',
                'MobilePhoneHome',
                'MobilePhoneWork',
                'LandPhoneGen',
                'LandPhoneHome',
                'LandPhoneWork',
            ];
            
            if (contacts) {
                html = '<p>Please select a phone number from your contact list</p><select class="nokiaphone_dropdown" style="height:100px;" multiple="multiple" >';
                for(var q=0;q<300;q++) {
                    var contact = contacts.getNext();
                    if (contact) {
                        var phoneNumber = null;
                        for (var g=0;g<validFields.length;g++) {
                            var key = validFields[g];
                            if (contact[key]) {
                                phoneNumber = contact[key].Value;
                                break;
                            }
                        }
                        var firstName = (contact.FirstName) ? contact.FirstName.Value : null;
                        var lastName = (contact.LastName) ? contact.LastName.Value : null;
                        if (!firstName && !lastName) {
                            if (!contact.CompanyName) {
                                firstName = phoneNumber;
                            } else {
                                firstName = CompanyName.Value;
                            }
                        }
                        var selected = (q == 0) ? 'selected="selected"' : '';
                        html += '<option value="'+phoneNumber+'" '+selected+'>'+firstName+' '+lastName+'</option>';
                    }
                }
                html += '</select><button class="smsNokiaApp">Send SMS</button>';
            } else {
                html = '<p>Please add a number to your contact list and try again.</p>';
            }
            
        } else {
            html = '<p>Please enter a phone number</p><table style="width:100%;"><tr>\
                <td style="vertical-align:middle; text-align:center; padding: 0 2px;">\
                    <input class="nokiaphone_cc" maxlength="3" type="text" value="" style="display:inline;width:2em;" /> \
                    - <input class="nokiaphone_area" maxlength="3" type="text"value="" style="display:inline;width:2em;" / > - \
                    <input class="nokiaphone_number" maxlength="32" type="text" value="" style="display:inline;width:8em;" />\
                    <br />Country Code, Area/City Code, and Number</td>\
                <td style="vertical-align:middle; padding: 0 2px;"><button class="smsNokiaApp">Send SMS</button></td>\
            </tr></table>';
        }

        var ui = $('<div style="text-align:center;width:100%;height:100%;position:absolute;z-index:10;top:0;left:0;background-color:#000;color:#fff;opacity:.9;">\
            <div class="modalmarkup" style="max-width:250px; padding:5px;margin: 10% auto 10px auto;background:#000;border:solid 1px #fff;">'+html+'</div>\
            <button class="modalclosebuton">Close</button>\
        </div>');
        
        var clickEvent = function(){
            var phoneNumbers = ($.currentPlatform() == "nokia") ? $('.nokiaphone_dropdown').val() : $('.nokiaphone_cc').val()+""+$('.nokiaphone_area').val()+""+$('.nokiaphone_number').val();
            if (typeof phoneNumbers == "string") { phoneNumbers = [phoneNumbers]; }
            var plength = phoneNumbers.length;
            var failedIndex = [];
            
            var sendMessage = function(index) {
                ui.find(".modalmarkup").text("Sending "+(index+1)+" of "+plength);
                $.servicePost("/transponder/sms/nokia", {
                    appId : $.transponder.getAppId(),
                    pn : phoneNumbers[index],
                    msg : o.smsText
                }, function() {
                    index += 1;
                    if (index < plength) {
                        sendMessage(index,phoneNumbers[index]);
                    } else {
                        ui.remove();
                        if (callback) { callback(); }
                    }
                }, function() {
                    index += 1;
                    failedIndex.push(index);
                    if (index < plength) {
                        sendMessage(index,phoneNumbers[index]);
                    } else {
                        var text = "SMS ";
                        for (var g=0;g<failedIndex.length;g++) {
                            text += failedIndex[g];
                            if (g < (failedIndex.length-2)) {
                                text += ",";
                            }
                            text += " ";
                            if (g == (failedIndex.length-2)) {
                                text += "and ";
                            }
                        }
                        text += "failed to send"
                        ui.find(".modalmarkup").text(text);
                        var timer = null, afterWait = function() {
                            clearTimeout(timer)
                            ui.find(".modalmarkup").append(html);
                            ui.find(".smsNokiaApp").bind("click",clickEvent);
                        };
                        timer = setTimeout(afterWait,700);
                    }
                });
            };
            
            sendMessage(0);
        };
        ui.find(".modalclosebuton").bind("click",function(){
            ui.remove();
            if (callback) { callback(); }
        });
        ui.find(".smsNokiaApp").bind("click",clickEvent);
        
        $('.container').append(ui);
    };
    
    // Helper Methods
    var openWindow = function(url, scrollbars, close, elem) {
        
        if ((typeof Facebook != "undefined" || $.currentPlatform() == 'iphone') && !$.isPreview()) {
            $(elem).attr("href", url);
            return true;  // iPhones dont like window.open.  instead use the h  
        } else {
            // Make all links open in a url
            if (window.widget) {
                window.widget.openURL(url);
            } else {
                var scroll = (scrollbars) ? 1 : 0;
                var newWindow = window.open(url,"TranspondShareService","scrollbars="+scroll+",resizable=1,menubar=0,location=0,toolbar=0,status=0,width=626,height=436");
                try {
                    if (window.focus) { newWindow.focus(); }
                    if (close && window.close) { newWindow.close(); }
                } catch(e) {
                    // Browser doesn't support focus and/or close
                }
            }
            
            return true;
        }
        
        return false;
    };
    
    // Plugin initialization
    // Images is an array of objects as follows:
    // {
    //     "src" : "http://www.google.com/myimagejpg",
    //     "href" : "http://www.google.com"
    // }
    $.newsfeed = function(platform, o, callback) {
        // Initialize options for this call
        var options = $.extend({
            "elem" : null,
            "prompt" : null,
            "userText" : null,
            "title" : null,
            "titleUrl" : null,
            "description" : null,
            "linkText" : null,
            "linkUrl" : null,
            "images" : [],
            "emailTo": null,
            "emailSubject" : null,
            "emailBody" : null,
            "targetId" : null,
            "smsText" : null
        },o);
        
        // Set global appUrl param
        for (var key in options) {
            if (options[key] != null && typeof options[key] == "string") {
                options[key] = options[key].replace("{appurl}",$.transponder.getAppUrl());
            }
        }
        
        var response = null;
        switch (platform) {
            case "email":
                response = email(options,callback);
            break;
            case "facebook":
                response = facebookFeed(options,callback);
            break;
            case "myspace":
                response = myspaceFeed(options,callback);
            break;
            case "twitter":
                response = twitterFeed(options,callback);
            break;
            case "nokia":
                response = nokiaSend(options,callback);
            break;
            default:
                // for now we do nothing. Later we will be sniffing for fbconnect and the like
                if (callback) {
                    callback();
                }
            break;
        }
        
        return response;
    };
    
})(jQuery);