//
// main variables
var dataObj = new Object();
var dataLoaded = false;
var initLoad = true;
var initContentShow = true;
var curPath = '';
var spinnerObj;
var initContentVal = '';
var scrollContent;
//
var timerUp = 0;
var timerDown = 0;
//
var galleryImageFolder = 'gallery/original/';
//
function spinner(holderid, R1, R2, count, stroke_width, colour) {
	
	
    var sectorsCount = count || 12,
        color = colour || "#fff",
        width = stroke_width || 15,
        r1 = Math.min(R1, R2) || 35,
        r2 = Math.max(R1, R2) || 60,
        cx = r2 + width,
        cy = r2 + width,
        r = Raphael(holderid, r2 * 2 + width * 2, r2 * 2 + width * 2),
        
        sectors = [],
        opacity = [],
        beta = 2 * Math.PI / sectorsCount,

        pathParams = {stroke: color, "stroke-width": width, "stroke-linecap": "round"};
        Raphael.getColor.reset();
    for (var i = 0; i < sectorsCount; i++) {
        var alpha = beta * i - Math.PI / 2,
            cos = Math.cos(alpha),
            sin = Math.sin(alpha);
        opacity[i] = 1 / sectorsCount * i;
        sectors[i] = r.path([["M", cx + r1 * cos, cy + r1 * sin], ["L", cx + r2 * cos, cy + r2 * sin]]).attr(pathParams);
        if (color == "rainbow") {
            sectors[i].attr("stroke", Raphael.getColor());
        }
    }
    var tick;
    (function ticker() {
        opacity.unshift(opacity.pop());
        for (var i = 0; i < sectorsCount; i++) {
            sectors[i].attr("opacity", opacity[i]);
        }
        r.safari();
        tick = setTimeout(ticker, 1000 / sectorsCount);
    })();
    return function () {
        clearTimeout(tick);
        r.remove();
    };
	
	
}
//

//
function unserialize (data) {
    // http://kevin.vanzonneveld.net
    // +     original by: Arpad Ray (mailto:arpad@php.net)
    // +     improved by: Pedro Tainha (http://www.pedrotainha.com)
    // +     bugfixed by: dptr1988
    // +      revised by: d3x
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +        input by: Brett Zamir (http://brett-zamir.me)
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: Chris
    // +     improved by: James
    // +        input by: Martin (http://www.erlenwiese.de/)
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: Le Torbi
    // +     input by: kilops
    // +     bugfixed by: Brett Zamir (http://brett-zamir.me)
    // -      depends on: utf8_decode
    // %            note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %            note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *       example 1: unserialize('a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}');
    // *       returns 1: ['Kevin', 'van', 'Zonneveld']
    // *       example 2: unserialize('a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}');
    // *       returns 2: {firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'}

    var that = this;
    var utf8Overhead = function(chr) {
        // http://phpjs.org/functions/unserialize:571#comment_95906
        var code = chr.charCodeAt(0);
        if (code < 0x0080) {
            return 0;
        }
        if (code < 0x0800) {
             return 1;
        }
        return 2;
    };


    var error = function (type, msg, filename, line){throw new that.window[type](msg, filename, line);};
    var read_until = function (data, offset, stopchr){
        var buf = [];
        var chr = data.slice(offset, offset + 1);
        var i = 2;
        while (chr != stopchr) {
            if ((i+offset) > data.length) {
                error('Error', 'Invalid');
            }
            buf.push(chr);
            chr = data.slice(offset + (i - 1),offset + i);
            i += 1;
        }
        return [buf.length, buf.join('')];
    };
    var read_chrs = function (data, offset, length){
        var buf;

        buf = [];
        for (var i = 0;i < length;i++){
            var chr = data.slice(offset + (i - 1),offset + i);
            buf.push(chr);
            length -= utf8Overhead(chr); 
        }
        return [buf.length, buf.join('')];
    };
    var _unserialize = function (data, offset){
        var readdata;
        var readData;
        var chrs = 0;
        var ccount;
        var stringlength;
        var keyandchrs;
        var keys;

        if (!offset) {offset = 0;}
        var dtype = (data.slice(offset, offset + 1)).toLowerCase();

        var dataoffset = offset + 2;
        var typeconvert = function(x) {return x;};

        switch (dtype){
            case 'i':
                typeconvert = function (x) {return parseInt(x, 10);};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'b':
                typeconvert = function (x) {return parseInt(x, 10) !== 0;};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'd':
                typeconvert = function (x) {return parseFloat(x);};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'n':
                readdata = null;
            break;
            case 's':
                ccount = read_until(data, dataoffset, ':');
                chrs = ccount[0];
                stringlength = ccount[1];
                dataoffset += chrs + 2;

                readData = read_chrs(data, dataoffset+1, parseInt(stringlength, 10));
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 2;
                if (chrs != parseInt(stringlength, 10) && chrs != readdata.length){
                    error('SyntaxError', 'String length mismatch');
                }

                // Length was calculated on an utf-8 encoded string
                // so wait with decoding
                readdata = that.utf8_decode(readdata);
            break;
            case 'a':
                readdata = {};

                keyandchrs = read_until(data, dataoffset, ':');
                chrs = keyandchrs[0];
                keys = keyandchrs[1];
                dataoffset += chrs + 2;

                for (var i = 0; i < parseInt(keys, 10); i++){
                    var kprops = _unserialize(data, dataoffset);
                    var kchrs = kprops[1];
                    var key = kprops[2];
                    dataoffset += kchrs;

                    var vprops = _unserialize(data, dataoffset);
                    var vchrs = vprops[1];
                    var value = vprops[2];
                    dataoffset += vchrs;

                    readdata[key] = value;
                }

                dataoffset += 1;
            break;
            default:
                error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
            break;
        }
        return [dtype, dataoffset - offset, typeconvert(readdata)];
    };
    
    return _unserialize((data+''), 0)[2];
}
function utf8_decode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Norman "zEh" Fuchs
    // +   bugfixed by: hitwork
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
    
    str_data += '';
    
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
}
//

//
// begin quotes slideshow
var quotesRunning = true;
var quoteNum = 7;
var quotesInit = true; 
var quotesTimer;
function handleQuotes() {  
	var numQuotes = 8;      
	var quoteID = "#quote"+quoteNum; 
	$(quoteID).fadeOut('fast', function() {
		quoteNum++;
		if (quoteNum >= numQuotes) {
			quoteNum = 0;
		}
		quoteID = "#quote"+quoteNum;
		$(quoteID).fadeIn('fast'); 
		if (quotesRunning) {
			quotesTimer = setTimeout(handleQuotes, 5000);
			//hideQuotes();
			//setTimeout(showQuotes, 10000);
		} 
	});	
}

function hideQuotes() {
	//$("#quotes").fadeOut('slow', function() {
	$("#quotes").animate({
		    opacity: 0
		  }, 500, 'easeOutExpo');
	quotesRunning = false;
	clearTimeout(quotesTimer);
}                

function showQuotes() {
	quotesRunning = true;
	clearTimeout(quotesTimer);
	if (quotesInit) {
		quotesInit = false;
		handleQuotes();
	} else {
		setTimeout(handleQuotes, 5000);
	}
	$("#quotes").animate({
		    opacity: 100
		  }, 500, 'easeOutExpo');
} 
// end quotes slideshow
//


//
// begin main menu 
function initializeMenu() {
	$("#galleriesMenu").click(function() {
		window.location = "#!galleries";
	});
	$("#galleriesMenu").bind('mouseover', mainMenuOver);
	$("#galleriesMenu").bind('mouseout', mainMenuOut);
	//
	$("#infoMenu").click(function() {
		window.location = "#!info/Bio";
	});
	$("#infoMenu").bind('mouseover', mainMenuOver);
	$("#infoMenu").bind('mouseout', mainMenuOut);
	//
	$("#contactMenu").click(function() {
		window.location = "#!info/Contact";
	});
	$("#contactMenu").bind('mouseover', mainMenuOver);
	$("#contactMenu").bind('mouseout', mainMenuOut);
	/*
	$("#blogMenu").click(function() {
		window.open("http://blog.jeffascough.com");
	});
	$("#blogMenu").bind('mouseover', mainMenuOver);
	$("#blogMenu").bind('mouseout', mainMenuOut);
	*/
	//
	var marginBottomVal = -50 * 900 / $(window).height();
	if (mobileMode) {
		marginBottomVal = -200;
		$("#galleriesMenu .label").css("color", "#000");
		$("#galleriesMenu .label").css("font-size", "2.8em");
		$("#infoMenu .label").css("color", "#000");
		$("#infoMenu .label").css("font-size", "2.8em");
		$("#contactMenu .label").css("color", "#000");
		$("#contactMenu .label").css("font-size", "2.8em");
	}
	$("#galleriesMenu").css("marginBottom", marginBottomVal);
	$("#infoMenu").css("marginBottom", marginBottomVal);
	$("#blogMenu").css("marginBottom", marginBottomVal);
	$("#contactMenu").css("marginBottom", marginBottomVal);
	//
	var menuMarginTop = -(268 * 3 + marginBottomVal * 2) / 2;
	$("#mainMenu").css("marginTop", menuMarginTop);
	//
	// hide sub menu items
	$.each($('#subGalleriesMenu').children(), function(index, value) { 
		var item = value;
		$(item).hide();	
	});
	$.each($('#pagesMenu').children(), function(index, value) { 
		var item = value;
		$(item).hide();	
	});
	//
}

function mainMenuOver() {
	$(this).addClass("over");
}

function mainMenuOut() {
	$(this).removeClass("over");
}

function showMainMenu() {
	$("#mainMenu").css('display', 'inline');
	setTimeout(function() { 
		$("#galleriesMenu").animate({
		    marginLeft: -400
		  }, 500, 'easeOutExpo');
		}, 
	100);
	setTimeout(function() {
		$("#infoMenu").animate({
		    marginLeft: -405
		  }, 500, 'easeOutExpo');
		}, 
	350);
	setTimeout(function() {
		$("#blogMenu").animate({
		    marginLeft: -400
		  }, 500, 'easeOutExpo');
		}, 
	600);
	setTimeout(function() {
		$("#contactMenu").animate({
		    marginLeft: -400
		  }, 500, 'easeOutExpo');
		}, 
	600);
}

function hideMainMenu() {
	setTimeout(function() { 
		$("#galleriesMenu").animate({
		    marginLeft: 5
		  }, 200, 'easeInExpo');
		}, 
	0);
	setTimeout(function() {
		$("#infoMenu").animate({
		    marginLeft: 5
		  }, 200, 'easeInExpo');
		}, 
	50);
	setTimeout(function() {
		$("#blogMenu").animate({
		    marginLeft: 5
		  }, 200, 'easeInExpo');
		}, 
	100);
	setTimeout(function() {
		$("#contactMenu").animate({
		    marginLeft: 5
		  }, 200, 'easeInExpo');
		}, 
	100);
	setTimeout(function() {
		$("#mainMenu").css('display', 'none');
	}, 100);
}
// end main menu
//  


//
// start pages menu
function showPagesMenu(id) {
	if (id == undefined) {
		var m = $("#pagesMenu");
	} else {
		var m = $(id);
	}
	var windowHeight = $(window).height();
	var topMarginVal = 400 + windowHeight/2 - 169 - Math.random() * 50;
	if (id == undefined) {
		topMarginVal = -windowHeight/2 - 169 - Math.random() * 50;
	}
	var leftTilt = true;
	$.each(m.children(), function(index, value) { 
		var item = value;
		if (mobileMode) {
			item.endTopMargin = topMarginVal + 169 + 80 * index;
		} else {
			item.endTopMargin = topMarginVal;
		}
		setTimeout(function() { 
			$(item).animate({
			    marginTop: item.endTopMargin
			  }, 500, 'easeOutExpo');
			}, 
		index * 200); 
		$(item).css('display', 'inline');
		if (mobileMode) {
			$(item).css('marginLeft', ($(window).width()) / 2);
		} else {
			$(item).css('marginLeft', 280 * index);
		}	
		if (leftTilt) {
			if (Math.random() > .5) {
				$(item).addClass('leftTiltStrong');
			} else {
				$(item).addClass('leftTilt');
			}
		} else {
			if (Math.random() > .5) {
				$(item).addClass('rightTiltStrong');
			} else {
				$(item).addClass('rightTilt');
			}
		}
		leftTilt = !leftTilt;
		//
		// center label
		//$(item).find('.pageLabel').css('marginLeft', Math.round((275 - $(item).find('.pageLabel').innerWidth()) / 2));
	});
	//
	var marginVal = -100
	if ($.browser.msie) {
		marginVal = -390;
	}
	if (id == undefined || id == "#subGalleriesMenu") {
 		$("#homeBtn").animate({
			marginTop: marginVal
		}, 200, 'easeOutExpo');
		$("#homeBtn").fadeIn("fast");
		
	}
	/* else {
		$("#backBtn").css('display', 'inline');
		$("#backBtn").animate({
			marginTop: marginVal,
			display: 'inline'
		}, 500, 'easeOutExpo');
	}
	*/
	//
	// center label
	//$("#homeBtn").find('.pageLabel').css('marginLeft', Math.round((275 - $("#homeBtn").find('.pageLabel').outerWidth()) / 2));
	//
	// center label
	//$("#backBtn").find('.pageLabel').css('marginLeft', Math.round((275 - $("#backBtn").find('.pageLabel').outerWidth()) / 2));
}

function hidePagesMenu(id, pageName) {
	if (id == undefined) {
		var m = $("#pagesMenu");
	} else {
		var m = $(id);
	}
	var windowHeight = $(window).height();
	$.each(m.children(), function(index, value) {
		var item = value;
		var thisLabel = $(item).find('.pageLabel').html();
	 	if (thisLabel.indexOf(pageName) > -1) {
			//
			// slides left
			var topMarginVal = 400 + windowHeight/2 - 169 - Math.random() * 50;
			if (id == undefined) {
				topMarginVal = -windowHeight/2 - 169 - Math.random() * 50;
			}
			setTimeout(function() { 
				$(item).animate({
				    marginLeft: 0,
					marginTop: topMarginVal
				  }, 500, 'easeInOutExpo');
				}, 
			m.children().length * 200);
			$(item).css('display', 'inline');
		} else {
			//
			// slide down or up
			var topMarginVal = 0;
			if (id == undefined) {
				topMarginVal = -topMarginVal;
			}
			setTimeout(function() { 
				$(item).animate({
				    marginTop: topMarginVal
				  }, 200, 'easeInExpo');
				}, 
			index * 200); 
			setTimeout(function() {
				$(item).css('display', 'none');
			}, 400);
		}
	});
	//
	//if (id == undefined) {
		//
		
		$("#homeBtn").animate({
			marginTop: 50
		}, 500, 'easeOutExpo');
		
		$("#homeBtn").fadeOut("slow");
		
		//
	//} else {
		//
		/*
		$("#backBtn").animate({
			marginTop: 50,
			display: 'none'
		}, 500, 'easeOutExpo');
		*/
		//
	//}
}

// end pages menu
//

//
// initial stuff...
$(document).ready(function() {
	//
	//spinnerObj = spinner("loadingIcon", 7, 10, 12, 2, "#000")
	showContentSpinner();
	//
	var rootTitle = $.address.title();
	$.address.change(function(event) {
		//alert(event.value);
       	handleContent(event.value); 
		if (event.value != 'home' && event.value != '' && event.value != '/') {
			$.address.title(event.value.split('/').join(' - ') + ' - ' + rootTitle); 
		} else {
			$.address.title(rootTitle) 
		}
		$.address.tracker();
    });
   	//
	initializeMenu();
	$("#index-content").empty();
	if ($.browser.msie) {
		/*
		$("#homeBtn").empty();
		$("#homeBtn").html('<div class="pageLabel"><a href="#">home</a></div>');
		$("#backBtn").empty();
		$("#backBtn").html('<div class="pageLabel"><a href="#info">back</a></div>');
		*/
	}
	if (mobileMode) {
		setupMobileUI();
	}
	//
	// iscroll initialization for ipad
	//document.addEventListener('touchmove', function(e){ e.preventDefault(); }, false);
	//
	$(window).resize();
});

//
$(window).load(function() {
	
	// get json data for site
	$.getJSON('inc/fget_json.php', function(data) {
	  	dataObj = data;
		dataLoaded = true;
		//
		$("#loadingIcon").empty();
		//
		handleContent(initContentVal);
	});
	$("#siteCanvas").css("opacity", 1);
	$("#paperLoader").empty();
	
});
  
//
// jquery address stuff..
function handleContent(val) {
	//alert(curPath + ', ' + val + ', ' + initLoad);
	if (curPath == val || initLoad) {
		if (initLoad) {
			initContentVal = val;
			initLoad = false;
		}
		return;
	}
	curPath = val;
	var paths = val.split('/');;
	if (paths[0] == 'home' || val == '' || val == '/') {  
		//
		showMainMenu();
		hidePagesMenu();
		hidePagesMenu('.subPagesMenu');
		hidePagesMenu('#subGalleriesMenu');
		$("#content_inner").fadeOut('fast', function(){
			$("#content_inner").empty();
		});
		showQuotes();
		$("#galNav").fadeOut('fast');
		$("#smallMenu").fadeOut('fast');
		//
	} else if (val == '/info') {
		//
		hideMainMenu();
		showPagesMenu();
		hidePagesMenu('.subPagesMenu');
		hidePagesMenu('#subGalleriesMenu');
		$("#content_inner").fadeOut('fast', function(){
			$("#content_inner").empty();
		});
		hideQuotes();
		$("#galNav").fadeOut('fast');
		$("#smallMenu").fadeIn('fast');
		//
	} else if (val == '/galleries') {
		//
		hideMainMenu();
		hidePagesMenu();
		hidePagesMenu('.subPagesMenu');
		$("#content_inner").fadeOut('fast', function(){
			$("#content_inner").empty();
		});
		showPagesMenu('#subGalleriesMenu');
		hideQuotes();
		$("#galNav").fadeOut('fast');
		$("#smallMenu").fadeIn('fast');
		//
	} else if (paths[3] != undefined) {
		//
		hideMainMenu();
		hidePagesMenu();
		hidePagesMenu('.subPagesMenu');
		hidePagesMenu('#subGalleriesMenu');
		$("#content_inner").fadeOut('fast', function(){
			handleGalleryContent(paths);
		});
		hideQuotes();
		$("#smallMenu").fadeIn('fast');
		//
	} else {
		//
		hideMainMenu();
		$("#content_inner").fadeOut('fast', function(){
			handlePageContent(paths);
		});
		hidePagesMenu('#subGalleriesMenu');
		hideQuotes();
		$("#galNav").fadeOut('fast');
		$("#smallMenu").fadeIn('fast');
	   	//
	}
	
	/*
	if (timerUp != undefined) {
		clearTimeout(timerUp);
	}
	if (timerDown != undefined) {
		clearTimeout(timerDown);
	}
	*/
}

function setupMobileUI() {
	//
	//  hide main menu images
	$("#galleriesMenu").css('background', 'transparent');
	$("#infoMenu").css('background', 'transparent');
	$("#contactMenu").css('background', 'transparent');
	//
	// hide sub page/gallery menu images
	$(".pageItem img").css("display", "none");
	$(".pageItem .label").css("width", "auto");
	//
	$("#galNav").css('font-size', '2em');
	$("#galNav").css('line-height', '.5em');
	$("#homeBtn").empty();
	$("#smallMenu").css('text-align', 'left');
	$("#smallMenu").css('marginLeft', '15px');
	$("#smallMenu").css('marginTop', '50px');
	
}

function handleHomeContent() {
	showMainMenu();
}

function handlePageContent(paths) {
	var pageName = paths[2];
	
	for (var i = 0; i<dataObj.pages.length; i++) {
		if (pageName == dataObj.pages[i].page_title) {
			var pageIndex = i;
			break;
		}
	}
	
	for (var i = 0; i<dataObj.pages.length; i++) {
		if (dataObj.pages[pageIndex].page_id == dataObj.pages[i].parent_id) {
			showPagesMenu("#pagesMenu"+dataObj.pages[pageIndex].page_id);
			hidePagesMenu();
			return;
		}
	}
	
	hidePagesMenu(null, pageName);
	hidePagesMenu('.subPagesMenu', pageName);
	
	hideContentSpinner();
	showContentSpinner();
	
	
	//
	var pageContent = "<div class='paper'>"; 
	pageContent += "<div class='inner'>";
	pageContent += "<div class='pageBack'><a href='#'><img src='assets/pageBackBtn.png' alt='back' /></a></div>";
	pageContent += "<div class='pageScroller'>";
	pageContent += "<div id='scrollUpBtn'></div>";
	pageContent += "<br />Scroll<br />";
	pageContent += "<div id='scrollDownBtn'></div>";
	pageContent += "</div>";
	pageContent += "<div class='pageText'>" + dataObj.pages[pageIndex].page_content + "</div>";
	pageContent += "</div>";
	pageContent += "</div>";
	//
	$("#content_inner").html(pageContent);
	var heightVal = $(window).height() - 200;
	if (heightVal > 640) {
		heightVal = 640;
	}
	
	if (pageName.toLowerCase().indexOf('contact') > -1) {
		$(".pageScroller").css('display', 'none');
	}
	if (mobileMode) {
		$(".pageScroller").css('display', 'none');
		$(".paper").width($(window).width());
		$(".pageText").css('height', 'auto');
		$(".paper").css('background', 'transparent');
	} else {
		$(".pageText").css("height", heightVal);
	}	
	if ($.browser.msie) {
		$("#content_inner").css("marginLeft", -250);
	} else {
		$("#content_inner").css("marginLeft", -250);
	}
	//scrollContent = new iScroll('content_inner');
	//
	$("#scrollUpBtn").mousedown(function() {
		//alert('up');
		scrollUpPage();
	});
	$('#scrollUpBtn').bind( "touchstart", function(e){
	    scrollUpPage();
	});
	$("#scrollUpBtn").mouseup(function() {
		clearTimeout(timerUp);
	});
	$('#scrollUpBtn').bind( "touchend", function(e){
	    clearTimeout(timerUp);
	});
	//
	$("#scrollDownBtn").mousedown(function() {
		//alert('down');
		scrollDownPage();
	});
	$('#scrollDownBtn').bind( "touchstart", function(e){
	    scrollDownPage();
	});
	$("#scrollDownBtn").mouseup(function() {
		clearTimeout(timerDown);
	});
	$('#scrollDownBtn').bind( "touchend", function(e){
	    clearTimeout(timerDown);
	});
	//
	if (mobileMode) {
		$("#content_inner").css('display', 'none');
		$("#content_inner").css('marginTop', '30px');
		$("#content_inner").fadeIn('slow');
		hideContentSpinner();
	} else {
		$("#content_inner").css('display', 'none');
		$("#content_inner").css('marginTop', 800);
		setTimeout(function() {
			$("#content_inner").fadeIn('slow');
			$("#content_inner").animate({
			    marginTop: 30
			  }, 500, 'easeOutExpo');
			hideContentSpinner();
		}, 600);
	}
	//
}

function scrollUpPage() {
	$(".pageText").scrollTop($(".pageText").scrollTop()-10);
	timerUp=setTimeout("scrollUpPage()",10);
}

function scrollDownPage() {
	$(".pageText").scrollTop($(".pageText").scrollTop()+10);
	timerDown=setTimeout("scrollDownPage()",10);
}

//
function handleGalleryContent(paths) {
	hideContentSpinner();
	showContentSpinner();
	var imageDoneLoading = false;
	//
	for (var i = 0; i<dataObj.categories.length; i++) {
		//if (paths[1] == dataObj.categories[i].category_name) {
			for (var j = 0; j<dataObj.galleries.length; j++) {
				if (paths[2] == dataObj.galleries[j].gallery_name && dataObj.galleries[j].category_id == dataObj.categories[i].category_id) {
					var catIndex = i;
					var galIndex = j;
					break;
				}
			}
		//}
	}
	//
	var imgNum = parseInt(paths[3]) - 1;
	//
	$("#content_inner").empty();  
	if (dataObj.galleries[galIndex].images[imgNum].image_file != undefined) {
		$("#content_inner").html("<img src='"+galleryImageFolder+dataObj.galleries[galIndex].images[imgNum].image_file+"' id='photo' style='display:none;' />"); //
		//
		$("#photo").load(function(){
			if (imageDoneLoading) {
				return;
			}
			$("#content_inner").fadeIn('slow');
			imageDoneLoading = true;
			handleImage();
			hideContentSpinner();
			//
		});

		if($("#photo")[0].complete){
			if (imageDoneLoading) {
				return;
			}
			$("#content_inner").fadeIn('slow');
			imageDoneLoading = true;
			handleImage();
			hideContentSpinner();
			//
		}  
	}  
	if (dataObj.galleries[galIndex].images.length > 1) {
		var lastNum = imgNum;
		if (lastNum == 0) {
			lastNum = dataObj.galleries[galIndex].images.length;
		}
		var nextNum = imgNum + 2;
		if (nextNum > dataObj.galleries[galIndex].images.length) {
			nextNum = 1;
		}
		var galNums = "<a href='#!galleries/" + dataObj.galleries[galIndex].gallery_name + "/" + (lastNum) + "'><img src='assets/gallery-nav-back.png' alt='<' class='navArrowLeft'/></a>";
		galNums += "<a href='#!galleries'>home</a>";
		galNums += "<a href='#!galleries/" + dataObj.galleries[galIndex].gallery_name + "/" + (nextNum) + "'><img src='assets/gallery-nav-next.png' alt='>' class='navArrowRight'/></a>"; 
		//
		$("#galNav").html(galNums);
		$("#galNav").fadeIn('fast'); 
	}
}
//
var c;
function handleImage() {
	//
	//handleImageLoaded();//$("#photo"));'
	//alert('handleImage');
	handleImageSizing();
	//$("#content_inner").css('display', 'none');
	//$("#content_inner").fadeIn('slow');
}
function handleImageSizing() {
	var contentWidth = $(window).width();
	var contentHeight = $(window).height();
	var imgWidth = $("#photo").width();
	var imgHeight = $("#photo").height();
	var padding = 80;
	if (mobileMode) {
		padding = 10;
	}
	//
	if (imgWidth > contentWidth - padding * 2) {
		imgWidth = contentWidth - padding * 2;
		imgHeight = $("#photo").height() * imgWidth/$("#photo").width();
	}
	padding = 80;
	if (imgHeight > contentHeight - padding * 2) {
		imgHeight = contentHeight - padding * 2;
		imgWidth = $("#photo").width() * imgHeight/$("#photo").height();
	}
	//
	// make raphael image holder
	
	var paper = Raphael("content_inner", contentWidth, contentHeight); 
	//paper.node.setAttribute("id", "content_inner");
	c = paper.image($("#photo").attr('src'), 0, 0, imgWidth, imgHeight);
	c.animate({opacity:100}, 5000, "<>"); 
	$("#content_inner").css('marginLeft', -imgWidth/2);
	$("#content_inner").css('marginTop', (contentHeight - imgHeight)/2);
	
}
window.onorientationchange = function() {
	$(window).resize();
}
$(window).resize(function() { 
	if (curPath.split('/')[0] == 'galleries') {
		handleImageSizing();
	}
	var w = $(window).width();
	var h = $(window).height();
	/*
	if (w < 1024) {
		$("#siteCanvas").css("width", "1024px");
	} else {
		$("#siteCanvas").css("width", "100%");
	}
	//
	if (h < 600) {
		$("#siteCanvas").css("height", "600px");
	} else {
		$("#siteCanvas").css("height", "100%");
	}
	*/
	//
	var windowHeight = h;
	
	//
	//alert('testing...');
	var topMarginVal = -windowHeight/2 - 160;//400-windowHeight/2 - 169 - Math.random() * 50;
	$.each($('#pagesMenu').children(), function(index, value) { 
		var item = value;
		positionMenuItem(item, topMarginVal);	
	});
	//
	topMarginVal = windowHeight/2 + 190;
	$.each($('#subGalleriesMenu').children(), function(index, value) { 
		var item = value;
		positionMenuItem(item, topMarginVal);	
	});
	//$(item).css('display');
	//
});

function positionMenuItem(item, topMarginVal) {
	if ($(item).css('display') != 'none') {
		if (!mobileMode) {
			//alert('topMarginVal: '+topMarginVal);
			item.endTopMargin = topMarginVal;
		}
		/*$(item).animate({
		    marginTop: item.endTopMargin
		  }, 500, 'easeOutExpo'); */
		$(item).css("marginTop", topMarginVal);
	}
}

function showContentSpinner() {
	//$("#contentLoadingIcon").css('margin-left', $("#content").width() - 10);
	if (!$.browser.msie) {
		spinnerObj = spinner("loadingIcon", 7, 10, 12, 2, "#000");
	}
}
function hideContentSpinner() {
	$("#loadingIcon").empty();
}

