var queryData; //will store initial query data as a global var for submodule js to potentially use

$('.toggleBtn').live("click", function() {
    var $this = $(this);
    var toggleElem = $('#' + $this.attr("data-toggle"));
    if (toggleElem.is(":visible")) {
        toggleElem.slideUp();
    } else {
        toggleElem.slideDown();
    }
});

$('#listLeft ul li a').live("click", function() {
    if ($(this).hasClass("listLeftSelected")) {
        return false;
    }
    $('.listLeftSelected').removeClass("listLeftSelected");
    $(this).addClass('listLeftSelected');
    var objId = $(this).attr("data-id");
    var tab = $('.innerSelected').attr("data-slug");
    var formData = getSearchFormJSON();
    $('#textRight').text("Loading...");
    $('#bottomRight').text("Loading...");
    formData.object_id = objId;
    var urlString = JSONtoQueryString(formData);
    var urlString = JSONtoQueryString({
        'tab': tab,
        'object_id': objId
    });
    History.pushState(formData, "", urlString);
    $.getJSON("/m/get_details", {
        'tab': tab,
        'object_id': objId
    }, function(data) {
        $('#imageInside').css({'backgroundImage': 'url(' + data.main_image.thumb + ')'});
        $('#textRight').text(data.title).formatTitle();
        var urlComponent = "?tab=" + $('.innerSelected').attr("data-slug") + "&object_id=" + objId;
        var baseUrl = location.protocol + "//" + location.hostname + location.pathname; 
        var url = baseUrl + urlComponent;
        
//        var fb_url = url.replace("&", "&amp;");
//        $('#fb_like').attr("data-href", fb_url);
        var twitter_url = "https://twitter.com/share?url=" + encodeURIComponent(url) + "&title=" + encodeURIComponent(data.title);
        $('#twitterBtn').attr("href", twitter_url);
        $('#permalinkBtn').attr("href", url);
        var searchTerm = $('.searchListField').val();
        var html = data.html;
        html = "<div>" + html + "</div>"; //Wrap to make IE happy
//		globalFoo = html;
        if (searchTerm != '') {
            for (var i=0; i<searchTerm.split(" ").length; i++) {
                html = highlightWordsNoCase(html, searchTerm.split(" ")[i]);
            }
//            html = html.replace(searchTerm, "<span class='highlight'>" + searchTerm + "</span>");    
        }
        $('#bottomRight').html(html);

        postLoadQuery(); //parse query string params for post load actions
//            console.log(data);
    });
    return false;
});

function postLoadQuery() {
    if (queryData.hasOwnProperty("goto")) {
        var locationHash = queryData['goto'];
        var scrollTop = $('a[name=' + locationHash + ']').position().top;
        $(window).scrollTop(scrollTop); //FIXME!!
        delete queryData['goto'];
    }
/*
    if (queryData.hasOwnProperty("btn")) {
        var $btn = $('#' + queryData.btn);
        $btn.click();
        console.log($btn);
        delete queryData['btn'];
    }
*/
}

$('.lightboxNext').live("click", function(e) {
    var $i = $(this).data("image");
    $i.click();
});

$('.lightboxPrev').live("click", function(e) {
    var $i = $(this).data("image");
    $i.click();
});

$('.thumbsDetails').live("click", function(e) {
//    alert($(this).attr("data-bigimage"));
    var $that = $(this);
    var totalImages = $(this).parent().find(".thumbsDetails").length;
    var thisIndex = $(this).index();

    if (thisIndex < (totalImages - 1)) {
        var hasNext = true;
        var nextImage = $(this).parent().find(".thumbsDetails").eq(thisIndex + 1);
        var preloadImage = new Image();
        preloadImage.src = nextImage.attr("data-bigimage");
    }

    if (thisIndex > 0 && totalImages > 1) {
        var hasPrev = true;
        var prevImage = $(this).parent().find(".thumbsDetails").eq(thisIndex - 1);
    }
    var $lbox = $('#lightboxPanel');
    var $cont = $('<div />').addClass("lightboxContainer");
    var bigImage = $(this).attr("data-bigimage");
    var $img = $('<img />').attr("src", bigImage).addClass("lightboxImg");    
    $img.appendTo($cont);
    var imgWidth = parseInt($that.attr("data-width"));
    var imgHeight = parseInt($that.attr("data-height"));
    var lightboxWidth = imgWidth + 40;
    var lightboxHeight = imgHeight + 60;
    $lbox.width(lightboxWidth);
    $lbox.height(lightboxHeight);
    var viewportWidth = $(window).width();
    var viewportHeight = $(window).height();
    if (viewportHeight < lightboxHeight) {
        $lbox.height(viewportHeight - 40);
    }
    var lightboxTop = parseInt((viewportHeight - $lbox.height()) / 2);
    $lbox.css({'top': lightboxTop + "px"});
         
   

//    showLightbox($img);
    var title = $(this).hasAttr("title") ? $(this).attr("title") : '';
//    var $c = $('#lightboxContent');


    if (title != '') {    
      var $caption = $('<div />').addClass("lightboxCaption").text(title).appendTo($cont);
    }
    if (hasNext) {
        var $next = $('<div />').addClass("lightboxNext").text("next").data("image", nextImage).appendTo($cont);
    }
    if (hasPrev) {
        var $prev = $('<div />').addClass("lightboxPrev").text("prev").data("image", prevImage).appendTo($cont);
    }
    showLightbox($cont);
});

function hideLightbox() {
    $('#lightbox, #lightboxPanel').fadeOut(400);
}

function showLightbox($content) {
    if (!$('#lightbox').is("visible")) {
        $('#lightbox, #lightboxPanel').fadeIn(400);
    }
    $('#lightboxContent').empty().append($content);
}


$('.toggleNext').live("click", function(e) {
    e.preventDefault();
    var $next = $(this).next();
    if (!$next.is(":visible")) {
        $next.slideDown();
    } else {
        $next.slideUp();
    }
});

function highlightWordsNoCase(data, word)
{
  var regex = new RegExp("(" + word + ")", "gi");
  return data.replace(regex, "<span class='searchHighlight'>$1</span>");
}

/* Get a jquery <option> row for a sort field, requires s.operator, s.field_name, s.friendly_name */
function getOption(s) {
    return $('<option />').val(s.operator + s.field_name).text(s.friendly_name);
}

/* Get a Jquery List Row object for an item - requires item.id and item.title*/
function getLi(item) {
    var titleLength = 30;
    var $li = $('<li />').addClass("tabListItem");
    var $a = $('<a />').attr("href", '#').attr("data-id", item.id).appendTo($li);
//    console.log(item.title.length);
    var $span = $('<span />').text(item.title).appendTo($a);
    return $li;
}

$(function() {
    $('#lightbox, #closeImg').click(function() {
        hideLightbox();
    });


    /* search button toggle */
    $('.searchInnerField').hide();
    $('#searchInner').toggle(function() {
      $('.searchInnerField').slideDown();
    }, function() {
      $('.searchInnerField').slideUp();
    });
    /* search button end */


    $('#aboutBtn').click(function() {
        var about = $('#moduleAbout').html();
        var $content = $('<div />').addClass("aboutLightbox").html(about);
        showLightbox($content);
    });

    $('#addBtn').click(function() {
        var add = $('#moduleAdd').html();
        var $content = $('<div />').addClass("addLightbox").html(add);
        showLightbox($content);
    });

//    $('#listLeft ul li a').eq(0).click();
//    alert("hi");


    $('.tabCategory').click(function() {
        var $this = $(this);
        if ($this.hasClass('.innerSelected')) {
            return false;
        }
        
        $('.innerSelected').removeClass("innerSelected");
        $this.addClass("innerSelected");
        $('.displayedTab').removeClass("displayedTab");
        var tab = $this.attr("data-slug");
        var tabId = $this.attr("data-id");
        $('#tabText_' + tabId).addClass("displayedTab");
        doListLoading();
        $.getJSON("/m/get_tab", {
            'tab': tab,
//            'page_no': 1
        }, function(data) {
 //           $('#loadingList').hide();
 //           stopListLoading(data.page);
            /* begin if for has_list, ideally make into separate render function */
            if (data.has_list) {
                /* handle sort options on list */
                $select = $('#orderBySelect');
                $select.empty();
                var sorts = data.sorts;
                if (sorts.length == 0) { $select.hide(); } else { $select.show(); }
                for (var j=0; j<sorts.length; j++) {
                    var s = sorts[j];
                    var $opt = getOption(s);
                    $select.append($opt);
                }
                /* end handle sort */
                
//                $('#object_id').val('');
                $('#page_no').val('1');
                /* handle displaying initial list on page */
                $('#listForm').submit();
//                displayList(data.page.items);
                /* end display initial list */

            } else {
            /* end if has_list */
                $('#textRight').text(data.title).formatTitle();
                var $html = getNoListHtml(data.page.items);
                $('#bottomRight').empty().append($html);
                History.pushState({'tab': tab}, "", "?tab=" + tab);   
            }
        });
    });

    $('#orderBySelect').change(function(e) {
        $('#listForm').submit();
    });


    $('#searchListIcon').click(function() {
        $('#listForm').submit();
    });

/*
    $('.searchListField').keyup(function(e) {
        e.preventDefault();
        if (e.keyCode == 13) {
            $('#listForm').submit();
        }
    });
*/

    $('#listForm').submit(function(e) {
        return true;
        e.preventDefault();
        doListLoading();
//        var urlString = "?tab_id=" + $('.innerSelected').attr("data-id") + "&sort=" + sortString + "&search=" + searchTerm;
        var formData = getSearchFormJSON();
//        delete(formData.object_id);
        var urlString = JSONtoQueryString(formData);
//        console.log(urlString);
        History.pushState(formData, "", urlString);
        $.getJSON("/m/get_list", formData, function(data) {
            stopListLoading(data);
            displayList(data.items);
            $('#object_id').val('');            
        });  
    });


    $('#triangleUp').click(function() {
        goPreviousPage();
    });    

    $('#triangleDown').click(function() {
        goNextPage();
    });

    var State = History.getState();
//    console.log(State);
    
        
    queryData = QueryStringToJSON(State.hash);

    doState(queryData);

});



/*
this function will grow to be a monster. be gentle with it, ideally move state functions to a state namespace or so.
queryData:
    object_id
    tab
    sort
    search
    page
    
*/
function doState(queryData) {
//    console.log(queryData);
//    var tab_slug = queryData.tab;
//    alert(tab_slug);

    if (queryData.hasOwnProperty("page")) {
        $('#page_no').val(queryData.page);
    }
    if (queryData.hasOwnProperty("search")) {
        $('#searchList').val(queryData.search);
    }
    if (queryData.hasOwnProperty("object_id")) {
        $('#object_id').val(queryData.object_id);
    }
    if (queryData.hasOwnProperty("sort")) {
        $('#orderBySelect').selectOption(queryData.sort);
    }

    //FIXME TO USE ABOUT / NO ABOUT LOGIC BASED ON USER PREFS.
/*
    if (!queryData.hasOwnProperty("noAbout")) {
        $('#aboutBtn').click();
    }
*/
    if (queryData.tab == undefined || queryData.tab == '') {
//        alert("foo");
        var $tab = $('.defaultTab');
    } else {
        var $tab = $('.tabCategory[data-slug=' + queryData.tab + ']');
        if ($tab.length == 0) {
            $tab = $('.defaultTab');
        }
    }

    $tab.click();
}


/*
>>>var foo = {'var1': 'bar', 'var2': 'baz'}
>>> JSONtoQueryString(foo);
'?var1=bar&var2=baz'
*/
function JSONtoQueryString(obj) {
    var s = "?";
    for (var o in obj) {
        if (obj.hasOwnProperty(o)) {
            s += o + "=" + obj[o] + "&";
        }
    }
    return s.substring(0, s.length - 1);
}

/*
>>>var foo = "/something/bla/?var1=bar&var2=baz";
>>>QueryStringToJSON(foo);
{'var1': 'bar', 'var2': 'baz'}
*/
function QueryStringToJSON(qstring) {
    if (qstring.indexOf("?") == -1) {
        return {};
    }
    var q = qstring.split("?")[1];
    var args = {};
    var vars = q.split('&');
//    console.log(vars);
    for (var i=0; i<vars.length; i++) {
        var kv = vars[i].split('=');
        var key = kv[0];
        var value = kv[1];
        args[key] = value;
    }		
    return args;		
}

function displayList(items) {
    var state = QueryStringToJSON(History.getState().hash);
//    console.log(state);
    for (var i=0; i<items.length; i++) {
        var $li = getLi(items[i]);
        $('#listLeft ul').append($li);                
    }
    if (state.object_id == undefined || state.object_id == '') {
        $('#listLeft ul li a').eq(0).click();
    } else {
        var $a = $('#listLeft ul li a[data-id=' + parseInt(state.object_id) + ']');
        if ($a.length > 0) {
            $a.click();
        } else {
            $('#listLeft ul li a').eq(0).click();
        }
    }
}

function doListLoading() {
    $('.tabListItem').remove();
    $('#loadingList').show();
}

function stopListLoading(page) {
    $('#currPageNo').text(page.page_no);
    $('#totalPages').text(page.num_pages);
    $('#loadingList').hide();
    if (page.page_no == 1) {
        $('#triangleUp').hide();
    } else {
        $('#triangleUp').show();
    }
    if (page.page_no == page.num_pages) {
        $('#triangleDown').hide();
    } else {
        $('#triangleDown').show();
    }
}

function goNextPage() {
    var currPage = parseInt($('#currPageNo').text());
    var totalPages = parseInt($('#totalPages').text());
    if (currPage < totalPages) {
        getPage(currPage + 1);
    }
}

function goPreviousPage() {
    var currPage = parseInt($('#currPageNo').text());
    if (currPage > 1) {
        getPage(currPage - 1);
    }
}

function getPage(pageNo) {
    $('#page_no').val(pageNo);
    $('#listForm').submit();
/*
    doListLoading();
    $.getJSON("/m/get_list", {
        'tab_id': $('.innerSelected').attr("data-id"),
        'page': pageNo,
        'sort': $('#orderBySelect').val()    
    }, function(page) {
        stopListLoading(page);
        displayList(page.items);
    });
*/
}

function getNoListHtml(items) {
    var $rhs = $('<div />');
    for (var i=0; i<items.length; i++) {
        var $obj = getNoListItemHtml(items[i]);
        $rhs.append($obj);
    }
    return $rhs;  
}


function getNoListItemHtml(item) {
    if (item.hasOwnProperty("url")) {
        var $ret = $('<div />').addClass("noListItem");
        var $title = $("<div />").addClass("noListTitle").appendTo($ret);
        var $a = $('<a />').attr("href", item.url).addClass("orangeLink").text(item.text).appendTo($title);
        var $text = $("<div />").addClass("noListText").html(item.text).appendTo($ret);
    } else {
        var $ret = $('<div />').addClass("noListItem").addClass("collapsible");
        var $title = $("<div />").addClass("orange").addClass("toggleNext").text(item.title).appendTo($ret);
        var $text = $("<div />").addClass("noListText").addClass("hidden").html(item.text).appendTo($ret);
    }
    return $ret;
}

function getSearchFormJSON() {
    return {
        'tab': $('.innerSelected').attr("data-slug"),
        'sort': $('#orderBySelect').val() != '' ? $('#orderBySelect').val() : '',
        'search': $('#searchList').val(),
        'page': $('#page_no').val(),
        'object_id': $('#object_id').val()
    }    
}

jQuery.fn.formatTitle = function() {
    var txt = $(this).text();
    var fontSize;
//    alert(txt.length);
    if (txt.length < 32) {
        fontSize = 40;        
    } else if (txt.length < 60) {
        fontSize = 40;
    } else if (txt.length < 100) {
        fontSize = 30;
    } else {
        fontSize = 20;
    }
    this.css({'fontSize': fontSize + "px"});
}

jQuery.fn.selectOption = function(value) {
    var that = this;
    var options = that.find('option');
    options.each(function() {
        if ($(this).attr("value") == value) {
            $(this).attr("selected", "selected");
            return;
        }
    });
}

jQuery.fn.hasAttr = function(name) {  
   return this.attr(name) !== undefined;
};

//from: http://rosskendall.com/blog/web/javascript-function-to-check-an-email-address-conforms-to-rfc822

function isRFC822ValidEmail(sEmail) {

  var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
  var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
  var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
  var sQuotedPair = '\\x5c[\\x00-\\x7f]';
  var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
  var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
  var sDomain_ref = sAtom;
  var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
  var sWord = '(' + sAtom + '|' + sQuotedString + ')';
  var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
  var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
  var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
  var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
  
  var reValidEmail = new RegExp(sValidEmail);
  
  if (reValidEmail.test(sEmail)) {
    return true;
  }
  
  return false;
}
