var streamBoxPreload = [
    "../images/popup-top.png",
    "../images/popup-middle.png",
    "../images/popup-bottom.png",
    "../images/popup-button.png",
    "../images/popup-button-selected.png",
    "../images/popup-check.png"
];
var searchBoxPreload = [
    "../images/butn-bg-main-nav.png",
    "../images/glass-gradient-overlay.png"
];
var webAppPreload = [
    "../images/std-button-blue.png"
];
var IS_IPHONE = false;
var IV_NAV_OFFSET = 118;
var IV_IPHONE_NAV_OFFSET = 0;
var SCREEN_WIDTH = 320;
var SCREEN_HEIGHT = 480;

function cat_submit(pic_mode){
	var d=document;
	var cat=d.getElementById('cat_name');
	var st=cat[cat.selectedIndex].value;
	var dom=document.domain;
	if(st=='mostrecent'||st=='mostviewed'||st=='toprated'){
		d.getElementById('sort').value=st;
		if(pic_mode==null)
			 var path='http://'+dom+'/'+st+'/page=1';
		else 		
			var path='http://'+dom+'/'+st+'/galleries/page=1';
	}
	else if(pic_mode==null){
		var sort=d.getElementById('sort').value;
		var path='http://'+dom+'/'+sort+'/videos/'+st;
	}
	else {
		var sort=d.getElementById('sort').value;
		var path='http://'+dom+'/'+sort+'/gals/'+st;
	}
	window.location=path;
};

function set_items(num){
	var base_url="http://"+location.hostname;
	var path_name=location.pathname;
	createCookie('items_per_page',num,30,'');
	window.location=base_url+path_name;//forcereload
};

createCookie = function(name,value,days,type) {     
    if (days) {
      var exdate = new Date();
		exdate.setDate(exdate.getDate()+days);
      expiredat=exdate.toGMTString();
    }
    else { 
		var expiredat = '';
    }

    document.cookie = name+"="+value+";expires="+expiredat+"; path=/";

    if ( type == 'streamBox' ) {
		streamBoxSet(value); 
		streamBoxHideUnderlay(); 
    }
    
};

readCookie = function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
};

eraseCookie = function(name) {
    createCookie(name,"",-1,'');
};

jQuery(document).ready(function() {
    if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) 
        IS_IPHONE = true;
    
    window.onorientationchange = function() {
        switch(window.orientation) {
            case 0:
                document.body.setAttribute("orient", 'portrait');
                break;
            case 90:
                document.body.setAttribute("orient", 'landscape');
                break;
            case -90:
                document.body.setAttribute("orient", 'landscape');
                break;
        }
    };
    if (IS_IPHONE)
        window.onorientationchange();
        
    // if the image viewer exists on this page handle it
    if ($('#imageViewer').length)
        setupImageViewer();
    
    // if a search button on the page exists set up search box
    if ($('.doSearchButton').length)
        setupSearchBox();
        
    // if a categories box exists on the page set it up
    if ($('#do_cats').length)
        setupCategories();
    //
    if ($('#streamBox').length)
        setupStreamBox();

   if (IS_IPHONE)
        hideURLbar();
});

/***  IMAGE VIEWER STUFF ***/
function setupImageViewer() {
    window.initImageViewer = true;
    if (IS_IPHONE) {
        addEventListener("load", function() {
            setTimeout('imageViewerHideURLbar(); window.initImageViewer = false', 0);
        }, false);

        document.body.addEventListener("touchstart", function (e) {

                if (e.targetTouches.length != 1) return false;
                startX = e.touches[0].pageX;
                startY = e.touches[0].pageY;
            },
            false);

        document.body.addEventListener("touchmove", function (e) {
                offsetX = startX - e.touches[0].pageX;
                offsetY = startY - e.touches[0].pageY;
                if (offsetX > 100) {
						if (document.start == null) {
							document.start = 1;
                  }
						else {
							document.start += 1;
                  }
						if (document.start > 1 ) {
							return false;
                  }
                  imageViewerNext();
                }
                if (offsetX < -100) {
						if (document.start == null) {
							document.start = 1;
                  }
						else {
							document.start += 1;
                  }
						if (document.start > 1 ) {
							return false;
                  }
                  imageViewerPrev();
                }
            },
            false);
       document.body.addEventListener("touchend", function (e) {
                document.start = null;
                if (e.targetTouches.length > 0) return false;
               
            },
            false);


    }
    
    $('body').css('background-color', $('#imageViewer').css('background-color'));
    $('#imageViewer .next').click(imageViewerNext);
    $('#imageViewer .prev').click(imageViewerPrev);
    $('#imageViewer .save').click(function() {
        alert('Click and hold on the image to save');
    });
    
    $('#theImage').html('<img src="" />');
    $('#theImage img')[0].opacity = 0;
    $('#theImage img')[0].onload = function() { imageViewerHandleSizing(); };
    window.loadPrevImg = new Image();
    window.loadNextImg = new Image();
    
    window.loadImageViewer = function(images, start) {
        imageViewerArray = images;
        imageViewerCurrent = start;
        imageViewerLast = start;
        imageViewerLoadImage(window.imageViewerCurrent);
    };
    window.onOrientationChangePassthrough  = window.onorientationchange;
    window.onorientationchange = function() {
        imageViewerHandleSizing();
        if (window.onOrientationChangePassthrough !== undefined)
            window.onOrientationChangePassthrough();
    };
};


function imageViewerHideURLbar() {
    if (window.pageYOffset != IV_NAV_OFFSET)
        setTimeout('window.scrollTo(0, IV_NAV_OFFSET)', 100);
};

function imageViewerHandleSizing(doScroll) {
    imageViewerHideLoading();
    if (IS_IPHONE) {
        var imageOrient = ($('#theImage img').width() > $('#theImage img').height()) ? 'landscape' : 'portrait';
        
        // iphone in portrait mode
        if (window.orientation == 0) {
            switch (imageOrient) {
                case 'portrait':
                    $('#theImage img').css({width: '100%', height: 'auto', marginTop: '0' });
                    break;
                case 'landscape':
                    $('#theImage img').css({width: '100%', height: 'auto'});
                    $('#theImage img').css(
                        'marginTop',
                        Math.ceil(((SCREEN_HEIGHT-IV_IPHONE_NAV_OFFSET)/2) - ($('#theImage img').height()/2)) + 'px'
                    );
            }
        }
        // iphone in landscape mode
        else {
            switch (imageOrient) {
                case 'portrait':
                    $('#theImage img').css({width: 'auto', height: '290px', marginTop: '0', margin: '0 auto' });
                    break;
                case 'landscape':
                    $('#theImage img').css({width: '100%', height: 'auto', marginTop: '0' });
            }
        }

        if (!window.initImageViewer)
            imageViewerHideURLbar();
    }
};

function imageViewerShowLoading() { $('#imageViewer .loading').css('display', 'block'); };
function imageViewerHideLoading() { $('#imageViewer .loading').css('display', 'none'); };

function imageViewerLoadImage(num) {
    imageViewerShowLoading();
    if (window.scrollYoffset) {
        window.scrollTo(0, IV_NAV_OFFSET);
    }
    if (num > 1)
        window.loadPrevImg.src = imageViewerArray[num-1];
    if (num < imageViewerArray.length-2)
        window.loadNextImg.src = imageViewerArray[num+1];
    $('#theImage img').attr('src', window.imageViewerArray[num]);
    if (num < 1) {
        $('#imageViewer .prev').css('display', 'none');
        $('#imageViewer .next').css('display', 'block');
    }
    else if (num > imageViewerArray.length-2) {
        //if ($('#joinURL').length)
        //    window.location = $('#joinURL').val();
        $('#imageViewer .prev').css('display', 'block');
        $('#imageViewer .next').css('display', 'none');
    }
    else {
        $('#imageViewer .prev').css('display', 'block');
        $('#imageViewer .next').css('display', 'block');

    }
};

function imageViewerNext() {
    if (imageViewerCurrent < imageViewerArray.length-1) {
        imageViewerCurrent++;
        imageViewerLoadImage(imageViewerCurrent);
    }
};

function imageViewerPrev() {
    if (imageViewerCurrent > 0) {
        imageViewerCurrent--;
        imageViewerLoadImage(imageViewerCurrent);
    }
};

/*** SETUP SEARCH BOX ***/
function setupSearchBox() {
    var imgs = new Array();
    for (var i=0, l=searchBoxPreload.length;i<l;i++) {
        imgs.push(new Image());
        imgs[i].src = searchBoxPreload[i];
    }

    // setup cancel button inside the search box
    $('#searchBox .searchCancelButton').click(function() {
        searchCleanupHandlers();
        $('#searchBox .searchInput').val('');
        $('#searchBox').css('display', 'none');
    });
    
    // hook the search functionality up
    $('#searchBox .searchInput').keypress(function(e) {
        if (e.which == 13) {
            $('#searchBox').css('display', 'none');
            $('#searchBox form[name=searchBoxForm]')[0].submit();
        }
    });
    
    // attach to the doSearchButton(s) on the page 
    $('.doSearchButton').click(function(){
        //window.scrollTo(0, 51);
        $('#searchBox').css('display', 'block');
        var el = $('#searchBox .searchInput');
        el.css('color', '#999').val('search...').focus();
        el[0].cleanup = true;
        el.click(searchClearContent);
        el.keydown(searchClearContent);

    });
};
function setupCategories() {
    // attach to the categories link  by id  // hash = id  . = class
    $('#do_cats').click(function(){
        var el = document.getElementById('categories');
        var cat = document.getElementById('cat_name');
        if (el.style.display == 'block')
				$('#categories').css('display', 'none');
        else {
				$('#categories').css('display', 'block');
            cat.focus();
        }

       });
   
};

function searchClearContent() {
    searchCleanupHandlers();
    var el = $('#searchBox .searchInput');
    el.val('');
    el.css('color', '#000');
};
function searchCleanupHandlers() {
    var el = $('#searchBox .searchInput');
    if (el[0].cleanup) {
        el[0].cleanup = false;
        el.unbind('click', searchClearContent);
        el.unbind('keydown', searchClearContent);
    }
};

/*** STREAM BOX ***/
function setupStreamBox() {
    var underlayHTML = "<div style='display: none' id='streamBoxUnderlay'></div";
    var imgs = new Array();
    
    for (var i=0, l=streamBoxPreload.length;i<l;i++) {
        imgs.push(new Image());
        imgs[i].src = streamBoxPreload[i];
    }
    
    $('body').append(underlayHTML);
    if (IS_IPHONE) {
        $('#streamBoxUnderlay')[0].ontouchstart = function(e) {
            e.preventDefault();
            streamBoxHideUnderlay();
        }
    }
    else
        $('#streamBoxUnderlay').click(streamBoxHideUnderlay);
    
    $('#streamBox .streamOptions a').each(function(i) {
        if (IS_IPHONE) {
            this.ontouchstart = function(e) {
                e.preventDefault();
                streamBoxSet($(this).attr('rel'));
            };
            this.ontouchend = function(e) {
                e.preventDefault();
                createCookie('bitrate', $(this).attr('rel'), 14,'streamBox');
                streamBoxSet($(this).attr('rel'));
                setTimeout('streamBoxHideUnderlay()', 100);
            };
        }
        else {
            $(this).click(function() {
                createCookie('bitrate', $(this).attr('rel'), 14,'streamBox');
                streamBoxSet($(this).attr('rel'));
                setTimeout('streamBoxHideUnderlay()', 100);

            });
        }
    });
    
    $('.linkToStreaming').click(function() { streamBoxShow(); });


    var bitrate = readCookie('bitrate');
    if (bitrate != '3g' && bitrate != 'edge') {
		  bitrate = 'wifi';
        createCookie('bitrate', 'wifi', 30, 'streamBox');
    }
	 streamBoxSet(bitrate);

    // if the cookie is not set for streaming bitrate ask for it
    
    /*if (readCookie('bitrate') != null){
        streamBoxSet(readCookie('bitrate'));
    }
    else if ($('#streamBox').hasClass('initSetting')) {
        streamBoxShow();
    }*/
};

function streamBoxShow() {
    if (readCookie('bitrate') == null){
       streamBoxSet('wifi');
    }
 
    if ($('#streamBox').css('display') == 'none') {
        $('#streamBoxUnderlay').css('display', 'block');
        $('#streamBoxUnderlay').css('height', '' + (window.innerHeight + window.pageYOffset) + 'px');
        $('#streamBox').css('top', window.pageYOffset + (window.innerHeight/2 - $('#streamBox').height()/2));
        $('#streamBox').css('display', 'block');
    }
    else {
        $('#streamBox').css('display', 'none');
    }
};
function streamBoxHideUnderlay() {
    $('#streamBoxUnderlay').css('display', 'none');
    $('#streamBox').css('display', 'none');
};
function streamBoxSet(type) {
    $('#streamBox .streamOptions a').each(function() {
        if ($(this).attr('rel') == type) {
            $(this).addClass('selected');
        }
        else if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
        }
    });
    streamBoxFormSet(type);
};   
function streamBoxFormSet(type) {
	$('#streamform input[type=radio]').removeAttr('checked');
	$('#f_'+type).attr('checked', 'checked');
};

function hideURLbar() {
    if ($('#galleryViewer').length) {
		if (window.pageYOffset == 0){
        addEventListener("load", function() { setTimeout('window.scrollTo(0, 0)', 200); }, false);
		}
    }
    else
        return;

};

