﻿//var flickrFeedUrl = "http://api.flickr.com/services/feeds/photos_public.gne";
//var flickrFeedId = "51881128@N03";
//var flickrFeedId2 = "42460684@N02";

var flickrFeedUrl = "http://api.flickr.com/services/feeds/photoset.gne";
var flickrFeedId = "72157624935097463";
var flickrFeedId2 = "72157624934839933";
var flickrUserId = "51881128@N03";

var searchSoapQuery = 89;
var searchSoapQuery2 = 0;
var getFlickrFeed = false;
var getFlickrFeed2 = false;
var getService = true;
var isFinextraCommunityPhoto = false;
var photoStreamLength = 100;
var iCount = 0;

//--Gallery Settings--//
var thumbWidth = 52;
var thumbHeight = 52;
var imagesVisible = 3;
//--------------------//

//--Main Image Dimensions--//
var mainImageWidth = 241;
var mainImageHeight = 180;
var imagesVisible = 3;
var transitionInterval = 5000; //0 = off
//--------------------//
var mycarousel_itemList = [{}];
var webSite = "http://www.ebaday.com/"

function doServiceRequest(iFinextraAlbum) {

    var whichAlbum = "GetMontagePhotos";

    if (isFinextraCommunityPhoto) {
        whichAlbum = "GetLivePhotos";
    }
   
    $.ajax({
        url: "/webservices/service.asmx/" + whichAlbum,
        type: "POST",
        dataType: "json",
        data: "{AlbumID:" + iFinextraAlbum + "}",
        contentType: "application/json; charset=utf-8",
        complete: searchResult
    });
};

function searchResult(xData, status) {
    var a = jQuery.parseJSON(xData.responseText);
    if (status == "error" || status == null) {
        document.writeln(status);
    } else {
    $.each(a.d, function(i, item) {
        iCount++;

        if (!isFinextraCommunityPhoto) {
            var d = new Date(parseInt(item.Date.substr(6, 13)));
        }
        else {
            var d = new Date(parseInt(item.PubDate.substr(6, 13)));
        }
        d = dateFormat(d, "UTC:yyyy-mm-dd'T'HH:MM:ss");
        if (!isFinextraCommunityPhoto) {
            var image = { url: item.FileName, title: item.Caption, link: item.FileName, date_taken: d, id: iCount, type: "finextra" };
        }
        else {
            var image = { url: item.FileName, title: item.Caption, link: item.FileName, date_taken: d, id: iCount, type: "finextracommunity" };
        }        
        mycarousel_itemList.push(image);
    });
        sortDateArray(false);
    };
};


function typeCheck(x, id) {
    var urlString;
    var myMontage = $.query.get('montageset');

    urlString = "&id=" + id;
    if ('' != myMontage) {
        urlString = urlString + "&montageset=" + myMontage;
    }
//    if (x == "finextra")
//        return "/Gallery/Default.aspx?service=finextra" + urlString;
//    else {
//        return "/Gallery/Default.aspx?service=flickr" + urlString;
//    }
    return "/Gallery/Default.aspx?service=" + x + urlString;
}

function showAllImagesInGallery() {
    $('.imageCon').html('');
//    $('.imgCaption').html('');
    var loadFirstImage;
    //if we're wanting to view a specific image
    //i.e. if the user has clicked on an image in the home page
    //and we're wanting to view a bigger version of hte image in
    //the gallery page the we check out the value of "id" in the querystring
    var qsid = $.query.get('id');

    if (qsid == '') {
        loadFirstImage = true;        
    }
    else {
        loadFirstImage = false;
    }
    
    for (var x = 0; x < mycarousel_itemList.length; x++) {
        if (loadFirstImage == true) {
            showLargeImage(mycarousel_itemList[x].id);
            loadFirstImage = false;            
        }
        if (qsid != '' &&
                mycarousel_itemList[x].id == qsid) {
            showLargeImage(mycarousel_itemList[x].id);
            qsid = '';
        }

        jQuery('.filmstrip').append('<li><a href="#gallery" id="' + mycarousel_itemList[x].id + '" onClick="showLargeImage(' + mycarousel_itemList[x].id + ')"><div style="width=' + thumbWidth + 'px;height:' + thumbHeight + 'px;"><img src="' + mycarousel_itemList[x].url + '" width="' + thumbWidth + '" border="0" alt="' + mycarousel_itemList[x].title + '" style="overflow:hidden;" /></div><title="' + mycarousel_itemList[x].title + '" /></a></li>');
    };

    $('#photos').galleryView({
        filmstrip_size: imagesVisible,
        frame_width: thumbWidth,
        frame_height: thumbHeight,
        background_color: 'transparent',
        nav_theme: 'dark',
        border: 'none',
        show_captions: false,
        caption_text_color: 'black',
        transition_interval: transitionInterval
    });
};

function showLargeImage(id) {
    var imageIdFind = getId(id);    
    var myType = typeCheck(imageIdFind.type, imageIdFind.id);    
    var myUrl = webSite + myType ;

//use this for Text inside the photo image
//    $('.imageCon').html('<a href="' + myType + '"><span style="width:' + mainImageWidth + 'px;height:' + mainImageHeight + 'px;display:block;float:;left;"><img id="mainImage" src="' + imageIdFind.url + '" border="0" style="overflow:hidden;width:' + mainImageWidth + 'px;" /></span></a><div id="subTextBackground" align="center"></div><div id="subText" align="center">' + imageIdFind.title + '</div>');
    $('.imageCon').html('<a href="' + myType + '"><span style="width:' + mainImageWidth + 'px;height:' + mainImageHeight + 'px;display:block;float:;left;"><img id="mainImage" src="' + imageIdFind.url + '" border="0" style="overflow:hidden;width:' + mainImageWidth + 'px;" /></span>');


//Use this for text below the photo image - enure that there is a div called imgCaption
//    $('.imageCon').html('<a href="' + myType + '"><span style="width:' + mainImageWidth + 'px;height:' + mainImageHeight + 'px;display:block;float:;left;"><img id="mainImage" src="' + imageIdFind.url + '" border="0" style="overflow:hidden;width:' + mainImageWidth + 'px;" /></span></a>');
//    $('.imgCaption').html('<div id="subTextBackground" align="center"></div><div id="subText" align="center">' + imageIdFind.title + '</div>');

    //let's run our social bookmarking info
    //CreateSocialBookmarks(myUrl, imageIdFind.title);
    //NOT Necessary for Ebaday (At the moment...)
};

function getId(id) {
    for (var x = 0; x < mycarousel_itemList.length; x++) {
        if (mycarousel_itemList[x].id == id) {
            return mycarousel_itemList[x];
        };
    };
};

function CreateSocialBookmarks(url, title) {
    $('#shareIcon span').qtip(
      {
          content: '<a href="http://twitter.com/home/?status=' + title + ': ' + encodeURIComponent(url) + '" class="linkTwit">twitter</a> <a href="http://www.facebook.com/sharer.php?u=' + encodeURIComponent(url) + '&t=' + title + '" class="linkFace">facebook</a> <a href="http://digg.com/submit?phase=2&URL=' + encodeURIComponent(url) + '&title=' + title + '" class="linkDigg">digg</a> <a href="http://del.icio.us/post?url=' + encodeURIComponent(url) + '&title=' + title + '" class="linkDel">del.icio.us</a>', // Give it some content
          // 
          position: 'bottomLeft', // Set its position
          hide: {
              fixed: true // Make it fixed so it can be hovered over
          },
          style: {
              padding: '5px 5px', // Give it some extra padding
              name: 'cream', // And style it with the preset dark theme
              width: 100

          }
      });
};


jQuery(document).ready(function() {
    $('.imageCon').html('<img src="/externalevents/assets/spinner.gif" /> Loading');
    getPhotos("flickr");
});

function urlBuilder(type) {
    switch (type) {
        case "flickr":
            //return flickrFeedUrl + "?id=" + flickrFeedId + "&lang=en-us&format=json&jsoncallback=?";
            return flickrFeedUrl + "?set=" + flickrFeedId + "&nsid=" + flickrUserId + "&lang=en-us&format=json&jsoncallback=?"; break;
        case "flickr2":
            //return flickrFeedUrl + "?id=" + flickrFeedId2 + "&lang=en-us&format=json&jsoncallback=?";
            return flickrFeedUrl + "?set=" + flickrFeedId2 + "&nsid=" + flickrUserId + "&lang=en-us&format=json&jsoncallback=?"; break;
            break;
        default:
            return alert("Error");
    };
};

function getPhotos(type) {
    if (getFlickrFeed == true) {
        $.getJSON(urlBuilder(type), function(data) {
            $.each(data.items, function(i, item) {
                iCount++;
                var image = { url: item.media.m, title: item.title, link: item.link, date_taken: item.date_taken, id: iCount, type: "flickr" };
                mycarousel_itemList.push(image);
            });
            if (getFlickrFeed2 == true) {
                getPhotos("flickr2");
                getFlickrFeed2 = false;
            } else {
                getFlickrFeed = false;
                if (getService == true) {
                    if (searchSoapQuery > 0) {
                        doServiceRequest(searchSoapQuery);
                    }
                    if (searchSoapQuery2 > 0) {
                        doServiceRequest(searchSoapQuery2);
                    }
                    
                } else {
                    sortDateArray(false);
                };
            };
        });
    } else {
        if (getService == true) {
            if (searchSoapQuery > 0) {
                doServiceRequest(searchSoapQuery);
            }
            if (searchSoapQuery2 > 0) {
                doServiceRequest(searchSoapQuery2);
            }
        } else {
            jQuery('#mycarousel').html('No Images Requested');
        };
    };
};

function sortDateArray(bSortDescending) {
    mycarousel_itemList = mycarousel_itemList.splice(1, mycarousel_itemList.length);
    var sorted = false;
    var z = 0;
    while (!sorted) {
        sorted = true;
        z++;
        for (i = 0; i < mycarousel_itemList.length - z; i++) {
            var temp1, temp2;
            if (mycarousel_itemList[i].date_taken < mycarousel_itemList[i + 1].date_taken) {
                temp1 = mycarousel_itemList[i];
                temp2 = mycarousel_itemList[i + 1];
                mycarousel_itemList[i] = temp2;
                mycarousel_itemList[i + 1] = temp1;
                sorted = false;
            };
        };
    };
    //    mycarousel_itemList = mycarousel_itemList.splice(0, photoStreamLength);
    if (bSortDescending == true) {
        mycarousel_itemList.reverse();
    }
    showAllImagesInGallery();
};

function printArray() {
    for (var i = 0; i < mycarousel_itemList.length; i++) {
        $('body').append('<br />' + mycarousel_itemList[i].date_taken + '<img src="' + mycarousel_itemList[i].url + '"></img>');
    };
    $('body').append('<br /><br />');
};

/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/

var dateFormat = function() {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function(val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function(date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function(mask, utc) {
    return dateFormat(this, mask, utc);
};
