﻿dojo.provide("stenco.core");
dojo.declare("stenco.core", null, {
    local: function() {
        //        if (window.location.hostname.toString().indexOf('stage', 0) >= 0) {
        //            return 'http://stage.collegesportsvision.com/';
        //        }
        //        else if (window.location.hostname.toString().indexOf('localhost', 0) >= 0) {
        //            return 'http://localhost/CollegeSportsVision/';
        //        }
        //        else {
        //            return 'http://www.collegesportsvision.com/';
        //        }

    },
    constructor: function(args) {
        if (args != 'undefined' && args != null)
            dojo.safeMixin(this, args);
    },
    AddTweetThisButton: function(elmCon, tweetURL, tweetText) {
        var tweetScript = dojo.create("script", { src: "http://platform.twitter.com/widgets.js" }, elmCon, "last");
        var tweet = dojo.create("a", { href: "http://twitter.com/share", innerHTML: "Tweet" }, elmCon, "last");

        dojo.attr(tweet, "class", "twitter-share-button");
        dojo.attr(tweet, "data-count", "horizontal");
        dojo.attr(tweet, "data-via", "PowercatVision");
        dojo.attr(tweet, "data-url", tweetURL);
        dojo.attr(tweet, "data-text", tweetText);
    },
    AddFacebookLikeButton: function(elmCon, likeURL) {
        var tweetScript = dojo.create("script", { src: "http://connect.facebook.net/en_US/all.js#xfbml=1" }, elmCon, "last");
        var facebookLike = dojo.create("fb:like", { href: likeURL, layout: "button_count", width: "100", action: "like", font: "arial" }, elmCon, "last");
    },
    AddFacebookRecommendButton: function(elmCon, likeURL) {
        var tweetScript = dojo.create("script", { src: "http://connect.facebook.net/en_US/all.js#xfbml=1" }, elmCon, "last");
        var facebookLike = dojo.create("fb:like", { href: likeURL, action: "recommend", font: "arial" }, elmCon, "last");
    },
    AddFacebookRecommendNoPhotosButton: function(elmCon, likeURL) {
        var tweetScript = dojo.create("script", { src: "http://connect.facebook.net/en_US/all.js#xfbml=1" }, elmCon, "last");
        var facebookLike = dojo.create("fb:like", { href: likeURL, layout: "button_count", action: "recommend", font: "arial" }, elmCon, "last");
    },
    AddPageTrack: function(pathClicked) {
        if (window.location.hostname.toString().indexOf('stage', 0) < 0 && window.location.hostname.toString().indexOf('localhost', 0) < 0) {
            var _uacct = "UA-18245683-1";
            var pageTracker = _gat._getTracker(_uacct);
            if (pathClicked.indexOf('//') > 0) {
                pathClicked.replace('//', '/');
            }
            pageTracker._trackPageview(pathClicked);
        }
    },
    CreateServiceStore: function(url) {
        var myService = dojox.rpc.Service(url);
        var myServiceStore = dojox.rpc.ServiceStore({ service: myService });
    },
    CreatePayPalUrl: function(buttonId, itemName, selections, totalAmount, invoiceId) {
        //var sBaseURL = "https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&hosted_button_id=" + buttonId;
        var sBaseURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&hosted_button_id=" + buttonId;
        var sURL = "";
        //HTML Version of Buy / Pay Now button
        //<input type="hidden" name="cmd" value="_xclick">
        //<input type="hidden" name="business" value="bstenfors@stenco.net">
        //<input type="hidden" name="undefined_quantity" value="1">
        //<input type="hidden" name="item_name" value="Farm Trends - Farm History Management Software">
        //<input type="hidden" name="amount" value="250.00">
        //<input type="hidden" name="shipping" value="15.00">
        //<input type="hidden" name="no_shipping" value="2">
        //<input type="hidden" name="return" value="http://www.farmtrends.com/purchasemade.aspx">
        //<input type="hidden" name="cancel_return" value="http://www.farmtrends.com/purchasecancel.aspx">
        //<input type="hidden" name="no_note" value="1">
        //<input type="hidden" name="currency_code" value="USD">
        //<input type="hidden" name="weight" value="1">
        //<input type="hidden" name="weight_unit" value="lbs">
        //<input type="hidden" name="lc" value="US">
        //<input type="hidden" name="bn" value="PP-BuyNowBF">
        //<input type="hidden" name="invoice" value="123" />

        //Business Attribute
        sURL = sBaseURL + "&business=bstenf_1197867989_biz@stenco.net"
        //sURL = sBaseURL + "&business=bstenfors@stenco.net";
        //Default Quantity
        //sURL += "&undefined_quantity=1"
        //Item Name
        //sURL += "&item_name=KC Catbackers - Summerfest Registration " & GetSelectedOptions()
        sURL += "&item_name=" + itemName + " " + selections;
        //Amount
        sURL += "&amount=" + totalAmount;
        //sURL += "&amount=1.00"
        //No Shipping
        sURL += "&no_shipping=1";
        //Return URL
        sURL += "&return=http://www.CollegeSportsVision.com/school.aspx?theme=" + this.QuerySt('theme');
        //Cancel Return URL
        sURL += "&cancel_return=http://www.CollegeSportsVision.com/school.aspx?theme=" + this.QuerySt('theme');
        //No Note
        sURL += "&no_note=1";
        //Currency Code
        sURL += "&currency_code=USD";
        //lc
        sURL += "&lc=US";
        //bn
        sURL += "&bn=PP-BuyNowBF";
        //rm
        sURL += "&rm=2";
        //notify url
        sURL += "&notify_url=http://stage.CollegeSportsVision.com/PaymentProcessed.aspx";
        //Invoice / Customer #
        sURL += "&invoice=" + invoiceId;

        return sURL;
    },
    ConvertSymbols: function(value) {
        var newValue = value.replace(/%3A/g, ':');
        newValue = newValue.replace(/%2F/g, '/');
        newValue = newValue.replace(/%40/g, '@');
        newValue = newValue.replace(/%20/g, ' ');
        newValue = newValue.replace(/%3C/g, '<');
        newValue = newValue.replace(/%3E/g, '>');
        newValue = newValue.replace(/%23/g, '#');
        newValue = newValue.replace(/%2C/g, ',');
        newValue = newValue.replace(/%3A/g, ':');
        newValue = newValue.replace(/%2B/g, '+');
        newValue = newValue.replace(/%26/g, '&');
        newValue = newValue.replace(/%24/g, '$');
        newValue = newValue.replace(/%3B/g, ';');
        newValue = newValue.replace(/%3D/g, '=');
        newValue = newValue.replace(/%3F/g, '?');
        newValue = newValue.replace(/%7B/g, '{');
        newValue = newValue.replace(/%7D/g, '}');
        newValue = newValue.replace(/%7C/g, '|');
        newValue = newValue.replace(/%5E/g, '^');
        newValue = newValue.replace(/%7E/g, '~');
        newValue = newValue.replace(/%5B/g, '[');
        newValue = newValue.replace(/%5D/g, ']');
        newValue = newValue.replace(/%60/g, '`');

        return newValue;
    },
    ExpandPageHeight: function(page, height) {
        var pageHeight = dojo.animateProperty(
        {
            node: page, duration: 250,
            properties: {
                height: { start: 200, end: height }
            }
        });
        pageHeight.play();
    },
    FlipContainer: function(ctrl) {
        var sideBarPanel = dojo.byId(ctrl);
        dojo.empty(sideBarPanel);
        var anim = dojox.fx.flip({
            node: sideBarPanel,
            dir: "right",
            duration: 500
        });
        //                dojo.connect(anim, "onEnd", this, function() {

        //                    //var loggedInContainer =
        //                    //                    var welcomeLabel = dojo.create("label", { innerHTML: "Welcome, " + member.UName, id: "welcome_label" }, loginContainer);
        //                    //                    var spacerLabel = dojo.create("label", { innerHTML: "&nbsp;|&nbsp;" }, loginContainer);
        //                    //                    var accountDetailsLabel = dojo.create("label", { innerHTML: "View Account Details", style: "cursor:pointer;" }, loginContainer);
        //                    //                    dojo.connect(accountDetailsLabel, "onclick", function() {
        //                    //                        var homepage = new stenco.csv.homepage();
        //                    //                        homepage.ExpandHeadliner();

        //                    //                    });
        //                });
        anim.play();
    },
    GetGeoLocByIp: function() {
        dojo.xhrGet({
            url: "http://ipinfodb.com/ip_query.php",
            handleAs: "json",
            timeout: 10000,
            content: { output: 'json', timezone: 'false' },
            load: function(response) { alert(response); },
            error: function(error, args) { alert(error); }
        });
    },
    GeoLocating: function() {
        //alert(geoip_city());
        //alert(geoip_postal_code());
        //alert(geoip_region_name());
        //alert("lon: " + parseFloat(geoip_longitude()));
        //alert("lat: " + parseFloat(geoip_latitude()));
        var returnJson =
        { "location":
            [
                {
                    "city": geoip_city(),
                    "zip": geoip_postal_code().toString(),
                    "region": geoip_region().toString(),
                    "lon": parseFloat(geoip_longitude()).toString(),
                    "lat": parseFloat(geoip_latitude()).toString()
                }
             ]
        };
        console.log(returnJson);
        return dojo.toJson(returnJson);

    },
    GetDistanceBetweenLatLon: function() {
        var R = 6371; // km
        var dLat = (lat2 - lat1).toRad();
        var dLon = (lon2 - lon1).toRad();
        var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return d = R * c;
    },
    HidePages: function(ignorePage) {
        var self = this;
        var pages = dojo.query("[page]");
        dojo.forEach(pages, function(currentPage) {
            if (dojo.attr(currentPage, "page") != ignorePage) {
                dojo.style(currentPage, "display", "none");
            }
            else {
                self.ExpandPageHeight(ignorePage, 200);
            }
        });
    },
    HideDialog: function(diag) {
        var dialogToHide = dijit.byId(diag);
        dialogToHide.hide();
    },

    itemToJSON: function(store, item) {
        // summary: Function to convert an item into a JSON format.
        // store:
        //    The datastore the item came from.
        // item:
        //    The item in question.
        var json = {};
        if (item && store) {
            //Determine the attributes we need to process.
            var attributes = store.getAttributes(item);
            if (attributes && attributes.length > 0) {
                var i;
                for (i = 0; i < attributes.length; i++) {
                    var values = store.getValues(item, attributes[i]);
                    if (values) {
                        //Handle multivalued and single-valued attributes.
                        if (values.length > 1) {
                            var j;
                            json[attributes[i]] = [];
                            for (j = 0; j < values.length; j++) {
                                var value = values[j];
                                //Check that the value isn't another item. If it is, process it as an item.
                                if (store.isItem(value)) {
                                    json[attributes[i]].push(dojo.fromJson(itemToJSON(store, value)));
                                } else {
                                    json[attributes[i]].push(value);
                                }
                            }
                        } else {
                            if (store.isItem(values[0])) {
                                json[attributes[i]] = dojo.fromJson(itemToJSON(store, values[0]));
                            } else {
                                json[attributes[i]] = values[0] != null ? values[0] : '';
                            }
                        }
                    }
                }
            }
        }
        return dojo.toJson(json);
    },
    PopulateYearDropdown: function(elm) {
        var yearDropdown = dijit.byId(elm);
        var i = 0;
        var currentDate = new Date();
        var currentYear = currentDate.getFullYear();
        for (i = 0; i <= 4; i++) {

            yearDropdown.addOption({ label: currentYear + i, value: currentYear + i });
        }
    },
    QuerySt: function(ji) {
        hu = window.location.search.substring(1);
        gy = hu.split("&");
        for (i = 0; i < gy.length; i++) {
            ft = gy[i].split("=");
            if (ft[0] == ji) {
                return ft[1];
            }
        }
    },
    ShowDialog: function(diag) {
        var d = dijit.byId(diag);
        dojo.style(d, "overflow", "hidden");
        d.show();
    },
    ShowInProgress: function(value, msg) {

        var pd = new dijit.Dialog({
            title: msg,
            style: 'width:550px;'
        });

        var msgCon = dojo.create("div", { innerHTML: msg });
        var pb = new dijit.ProgressBar(
        {
            value: value,
            style: 'width:100%;'
        });
        pd.setContent(pb.domNode);
        pb.startup();
        pd.show();
    },
    WipeInPage: function(page, height) {

        this.HidePages();

        var wipeIn = dojo.fx.wipeIn({ node: page, duration: 250 });
        wipeIn.play();

        //this.ExpandPageHeight(page, height);
    }
});

