//(c) 2008 Michael Manning 
jQuery.parseQuery=function(A,B){var C=(typeof A==="string"?A:window.location.search),E={f:function(F){return unescape(F).replace(/\+/g," ")}},B=(typeof A==="object"&&typeof B==="undefined")?A:B,E=jQuery.extend({},E,B),D={};jQuery.each(C.match(/^\??(.*)$/)[1].split("&"),function(F,G){G=G.split("=");G[1]=E.f(G[1]);D[G[0]]=D[G[0]]?((D[G[0]] instanceof Array)?(D[G[0]].push(G[1]),D[G[0]]):[D[G[0]],G[1]]):G[1]});return D};

/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/

(function ($) {

$.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }
    
  return this.each(function () {
    // get jQuery version of 'this'
    var $input = $(this),
    
    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = $(this.form),
      $win = $(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title
      
      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};

})(jQuery);

smugscope  = function(){
	// Everything public goes in pub
	var pub = {};
	// Everything private is a 'var'
	var privStr = 'beforeInit';
	var querystringParams;
	var host_path = window.location.protocol + "//" + window.location.host + window.location.pathname;
	var querystring = window.location.search;
	var querystringBuild = '';
	
	var privAlert = function(){
	   //alert(privStr);
	}
	var getUrlBuild = function(){
	  return host_path + '?s=' + querystringBuild + pub.getNonSettingQuerystring();
	}
	pub.host_path = host_path;
	pub.querystringBuild = querystringBuild;
	pub.init = function(){
		querystringParams = $.parseQuery();
		if(typeof(querystringParams.s) != "undefined"){
			querystringBuild = querystringBuild + querystringParams.s;
			pub.querystringBuild = querystringBuild;
		}
		//privStr = 'afterInit';
		return this;
	};
	pub.querystringParams = function(){
		return querystringParams;
	}
	pub.getNonSettingQuerystring= function(){
		var qsp_u = '';
		var qsp_c = '';
		var qsp_d = '';
		if( typeof(querystringParams.u) != "undefined" ){
			qsp_u = '&u=' + querystringParams.u;
		}
		if( typeof(querystringParams.d) != "undefined" ){
			if(querystringParams.d == ''){
				qsp_d = '';
			}else{
				qsp_d = '&d=' + querystringParams.d;
			}
			
		}
		var uNew;
		try{
			uNew = $('#username_control_input').val().replace('Smugmug User Name...','');
			if(uNew != ''){
				qsp_u = '&u=' + uNew;
			}
		}catch(e){}
		try{
			uNew = $('#username_url_control_input').val().replace('Custom Domain...','');
			if(uNew == ''){
				qsp_d = '';
			}else{
				qsp_d = '&d=' + uNew;
			}
		}catch(e){}
		if( typeof(querystringParams.c) != "undefined" ){
			qsp_c = '&c=' + querystringParams.c;
		}
		return qsp_u + qsp_d + qsp_c;
	}
	/*pub.imageCluster = function(){
		$('.gallery_images_outer').each(function(){
			var albumIdKey = this.id.replace('gallery_images_outer_','');
			$.get(
				smugscope.host_path,
				{ 's':smugscope.querystringBuild + '.albums~'+albumIdKey, 'e':'viewer', 'u':'ephoto' },
				function(data){
				$(this).html( data );
			});
		});
	}*/
	pub.imageCluster = function(){
		/*$('#gallery_images_outer').each(function(){
			$.get(
				smugscope.host_path,
				{ 's':smugscope.querystringBuild , 'e':'viewer', 'u':'ephoto' },
				function(data){
				$(this).html( data );
			});
		});*/
		var onMouseOutOpacity = 0.67;
		$('#gallery_images ul.thumbs li').css('opacity', onMouseOutOpacity)
			.hover(
			function () {
				$(this).not('.selected').fadeTo('fast', 1.0);
			},
			function () {
				$(this).not('.selected').fadeTo('fast', onMouseOutOpacity);
			}
		);
		$.get(
			smugscope.host_path,
			{ 's':smugscope.querystringBuild , 'e':'viewer', 'u':'ephoto' },
			function(data){
			$('#gallery_images_outer').html( data );
		});
	}
	pub.getUrlBuild = function(){
		return getUrlBuild();
	};
	pub.removeParamDelims = function(searchVal){
		searchVal = searchVal.replace(/\./g,''); //remove param value delimiters
		searchVal = searchVal.replace(/~/g,''); //remove param value delimiters
		return searchVal;
	}
	pub.buildQuerystring = function(key, val){
		var re;
		var searchVal = $('#search_control_input').val();
		
		re = new RegExp('[.]' + 'offset~' + '(?:[^.]*)', 'gi'); //clear out offset
		querystringBuild = querystringBuild.replace(re, '');
		
		re = new RegExp('[.]' + 'step~' + '(?:[^.]*)', 'gi'); //clear out step
		querystringBuild = querystringBuild.replace(re, '');

		if(key == 'search' || key == 'searchop'){ //search and searchop are paired, so if one changes, process the other too
			if(searchVal == 'Search Words...'){
				searchVal = '';
			}
			if(searchVal == ''){
				re = new RegExp('[.]' + 'search~' + '(?:[^.]*)', 'gi');
				querystringBuild = querystringBuild.replace(re, '');
				
				re = new RegExp('[.]' + 'searchop~' + '(?:[^.]*)', 'gi');
				querystringBuild = querystringBuild.replace(re, '');
			}else{
				if(key == 'search'){
					if(key == 'search'){
						searchEncoded = '.search~' + encodeURI(val);
					}else{
						searchEncoded = '.search~' + encodeURI($('#search_control_input').val());
					}
					searchEncoded = searchEncoded.replace(' ', '+');
				}
				re = new RegExp('[.]' + 'search~' + '(?:[^.]*)', 'gi');
				querystringBuild = querystringBuild.replace(re, '') + searchEncoded;

				re = new RegExp('[.]' + 'searchop~' + '(?:[^.]*)', 'gi');
				querystringBuild = querystringBuild.replace(re, '') + '.searchop~' + $('#search_option_operator_control_select').val();
			}

			return;
		}

		re = new RegExp('[.]' + key + '(?:[^.]*)', 'gi');
		querystringBuild = querystringBuild.replace(re, '') + val;
		
	};
	pub.updateFilter = function(){
		var urlBuild = getUrlBuild();
		if( typeof(querystringParams.d) != "undefined" ){
			if(pub.querystringParams.d == ''){
				querystringBuild = querystringBuild.replaced('d=','');
			}
		}
		$('#filter_settings_display').empty().append( decodeURI(querystringBuild.replace(/[.]/g,'<br />').replace(/[~]/g,': ')) );
		if(querystringBuild != ''){
			$('#filter_settings_display').append('<br /><br /><div style="border-bottom:solid 1px gray"></div><br /><strong>Link to this Search</strong><br />&nbsp;&nbsp;<small style="font-size:.8em">(right click to copy)</small>:<br /><a href="' + urlBuild + '">' + urlBuild + '</a>');
			var urlBuildEncoded = encodeURIComponent(urlBuild);
			$('#filter_settings_display').append('<br /><br /><div style="border-bottom:solid 1px gray"></div><br /><a href="mailto:_ENTER_EMAIL_ADDRESS_?subject=photo@20gallery&body=' + urlBuildEncoded + '">' + 'Email this Search Link</a>');
		}
				
	};
	return pub;
}().init();


$(document).ready(function() {

	/*$('.gallery_pic > img').each(function(){
		$(this).attr('src', $(this).attr('rel'));
	});*/
	smugscope.buildQuerystring('search', $("#search_control_input").val());
	smugscope.updateFilter();
	$('input:text').hint();
	
	/*$(".keywords").accordion({
		collapsible: true,
		alwaysOpen: false,
		active: false,
		fillSpace: true
	});*/
	

	$('.keywords .head').click(function() {
		$(this).next().toggle('slow');
		return false;
	}).next().hide();

	$('.controls .head').click(function() {
		$(this).next().toggle('slow');
		return false;
	}).next().hide();
	
	//$('.keywords div div p').show();
	
	//smugscope.imageCluster();
	
	
	$('#username_url_control_metacontrol_link').click(function(){
		$('#username_url_control_span').toggle('slow');
		return false;
	});
	
	/*$('#username_url_control_input').change(function(){
		smugscope.buildQuerystring('search', searchVal);
		smugscope.updateFilter();
	});*/
	
	$('#categories_control_select').change(function(){
		smugscope.buildQuerystring('categories', $("#categories_control_select option:selected").val());
		smugscope.updateFilter();
	});
	
	$('#subcategories_control_select').change(function(){
		smugscope.buildQuerystring('subcategories', $("#subcategories_control_select option:selected").val());
		smugscope.updateFilter();
	});
	
	$('#sort_control_select').change(function(){
		smugscope.buildQuerystring('sort', $("#sort_control_select option:selected").val());
		smugscope.updateFilter();
	});
	
	$('#max_control_select').change(function(){
		smugscope.buildQuerystring('max', $("#max_control_select option:selected").val());
		smugscope.updateFilter();
	});
	
	$('#max_control_select').change(function(){
		smugscope.buildQuerystring('max', $("#max_control_select option:selected").val());
		smugscope.updateFilter();
	});
	
	$('#search_control_input').change(function(){
		searchVal = smugscope.removeParamDelims($("#search_control_input").val());
		$("#search_control_input").val(searchVal); //set delimiter safe value
		smugscope.buildQuerystring('search', searchVal);
		smugscope.updateFilter();
	});
	
	$('#search_option_operator_control_select').change(function(){
		smugscope.buildQuerystring('searchop', '.searchop~' + $("#search_option_operator_control_select").val());
		smugscope.updateFilter();
	});
	
	$('input').keyup(function(e) {
		if(e.keyCode == 13) {
			searchVal = smugscope.removeParamDelims($("#search_control_input").val());
			$("#search_control_input").val(searchVal); //set delimiter safe value
			$('#apply_filters').trigger('click');
		}
	});
	
	
	
	$('#apply_filters').click(function(){
		$('#galleries').prepend('<img id="progress_bar" src="smugscope.img.progress-bar.gif" />');
		$('#apply_filters').attr('value','PROCESSING...').attr('disabled','disabled');
		window.location = smugscope.getUrlBuild();
			/*$.get(
				smugscope.host_path,
				{ 's':smugscope.querystringBuild, 'template':'ajax_albums' },
				function(data){
					$('#galleries').html( data );
					//$('#progress_bar').remove();
					$('#apply_filters').attr('value','Apply Filter').attr('disabled','');
				});
			*/

	});
	
	/*var gallery = $('.gallery_images_outer').galleriffic('gallery_images_4749806_hEZjd', {
        delay:                  3000,
        numThumbs:              20,
        preloadAhead:           40, // Set to -1 to preload all images
        enableTopPager:         false,
        enableBottomPager:      true,
        imageContainerSel:      '',
        controlsContainerSel:   '',
        captionContainerSel:    '',
        loadingContainerSel:    '',
        renderSSControls:       true,
        renderNavControls:      true,
        playLinkText:           'Play',
        pauseLinkText:          'Pause',
        prevLinkText:           'Previous',
        nextLinkText:           'Next',
        nextPageLinkText:       'Next &rsaquo;',
        prevPageLinkText:       '&lsaquo; Prev',
        enableHistory:          false,
        autoStart:              false,
        onChange:               undefined, // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
        onTransitionOut:        undefined, // accepts a delegate like such: function(callback) { ... }
        onTransitionIn:         undefined, // accepts a delegate like such: function() { ... }
        onPageTransitionOut:    undefined, // accepts a delegate like such: function(callback) { ... }
        onPageTransitionIn:     undefined  // accepts a delegate like such: function() { ... }
    });*/

});
