var lsboxes, isini;
var cvar=[];

$(document).ready(function () {

	var searchBox = $("#navsearch");
	
	//Clear on first click
	if(searchBox.val().lastIndexOf('...') !== -1){
		cvar['defSearchBoxMsg'] = searchBox.val();
	}

	searchBox.focus(function(e){  
		$(this).addClass("activens");  
		if(cvar['defSearchBoxMsg'] != 'undefined' && $(this).val() == cvar['defSearchBoxMsg']) $(this).val('');
	});  

	searchBox.blur(function(e){  
		$(this).removeClass("activens");  
		if(cvar['defSearchBoxMsg'] != 'undefined' && $(this).val() == "") $(this).val(cvar['defSearchBoxMsg']);
	});


	//LSearch box + 'res' = LSearch results
	//Global Live Search
	lsboxes = $('#navsearch, #lscat');
	lsboxes.focus(function(){ if($(this).attr('value').length > 0) showResults('#'+$(this).attr('id')+'res'); });
	lsboxes.blur(function(){ $('#'+$(this).attr('id')+'res').slideUp('normal'); });
	lsboxes.keyup(function(){ preShowResult($(this).attr('value'), '#'+$(this).attr('id'), '#'+$(this).attr('id')+'res'); });
	lsboxes.each(function(){ fixLSPositions(this.id); $(this).attr('autocomplete','off'); });
	
	$('.selectallinput').focus(function(){
		this.select();
	});
    
    
    isini = false;
    if(window.location != window.parent.location) isini = true;
    if(isini == true){
        $('a').attr('target', '_top');
        if(typeof pageTracker != 'undefined')
            pageTracker._trackPageview('/1/gimg/' + encodeURIComponent(document.location.href));
    }

});


////////////////
// GALLERY //
////////////////
$('#listgallery').ready(function(){
    var maxH = 0;
    $('#listgallery ul').each(function(){
            maxH = ($(this).height() > maxH)?($(this).height()):(maxH);    
    });
    $('#listgallery ul').height(maxH);   
});

///////////////
// UPLOAD //
///////////////

$('#lscatres a,#navsearchres a').live('click',function(){
	$('#'+$(this).parent().attr('id').replace(/res$/, '')).val($(this).text());
	if($(this).parent().attr('id') == 'lscatres')	return false;
});
	
$(document).ready(function(){
	if($('#lscat').length == 1){
	if($('#lscat').val().lastIndexOf('...') !== -1){
		cvar['uploadLSname'] = $('#lscat').val();
	}
	
	$('#lscat').bind('focus',function(e){
		if(cvar['uploadLSname'] != 'undefined' && $(this).val() == cvar['uploadLSname']) $(this).val('');
	});
	
	$('#lscat').bind('blur',function(){
		if($(this).val() == '' && cvar['uploadLSname'] != 'undefined') $(this).val(cvar['uploadLSname']);
	});
	}
});


////////////////////
//LIVE SEARCH//
////////////////////

var xmlhttp;
var resid, sid;
var lstim = new Array();
var lsque = new Array();

function x(it){
	console.dir(it);
}

function preShowResult(str, tsid, tid){
	if(typeof $('#navsearch').data(str) != 'undefined'){
		clearTimeout(lstim[tsid]);
		showResults(tid, $('#navsearch').data(str));
		return;
	}
	if(typeof lsque[tsid] == 'undefined'){ lsque[tsid] = 0; }
	lsque[tsid]++;
	var curid = lsque[tsid];
	clearTimeout(lstim[tsid]);
	lstim[tsid] = setTimeout( function(){ if(lsque[tsid] == curid) showResult(str,tsid, tid); }, 500);
}

function showResult(str, tsid, tid){
	resid = tid;
   sid = tsid;
	
	if (str.length==0){
		$(resid).html('');
		$(resid).slideUp('normal');
		return;
	}

	xmlhttp=GetXmlHttpObject();
	if(xmlhttp==null){
		alert ("Your browser does not support XML HTTP Request");
		return;
	}

	var url="livesearch.php";
	url=url+"?q="+str;
	url=url+"&sid="+Math.random();
	if(tsid == '#navsearch') url=url+"&r=1";
	xmlhttp.onreadystatechange=stateChanged ;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}

function showResults(id, res){
	if(typeof res != 'undefined'){
		$(id).html(res);
	}

	if($(id).html().length > 0 && $(id).html() != '&nbsp;'){
		$(id).slideDown('normal');
		if($(id).css('display') == 'none') $(id).css('display','inline');
	}
}

function fixLSPositions(obj){
	var tempsid = $('#' + obj);
	var temprid = $('#' + obj + 'res');
	if(typeof tempsid !== 'undefined'){
		var offset;
		if(temprid.is('#navsearchres')){
			offset = tempsid.offset();
			offset.top += 5;
		}else{
			offset = tempsid.position();
			offset.top += (tempsid.outerHeight(false) / 2) - 1;
		}
		temprid.css('top', offset.top + tempsid.height() - 4);
		temprid.css('left', offset.left);
	}
}

function stateChanged(){
	if(xmlhttp.readyState==4){
		$('#navsearch').data($(sid).attr('value'), xmlhttp.responseText);
		$(resid).html(xmlhttp.responseText);
		
		if(xmlhttp.responseText.length > 0){
			$(resid).slideDown('normal');
			if($(resid).css('display') == 'none') $(resid).css('display','inline');
		}else{
			$(resid).slideUp('normal');
		}		
	}
}

function GetXmlHttpObject(){
	if(window.XMLHttpRequest)
		return new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
	if(window.ActiveXObject)		
		return new ActiveXObject('Microsoft.XMLHTTP'); // code for IE6, IE5
	return null;
}

//COOKIE
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined'){
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



var GSFN;
if(GSFN == undefined) {
  GSFN = {};
}
 
if(!GSFN.initialized) {
  GSFN.loadedcss = false;
  GSFN.gId = function(id) {
    return document.getElementById(id);
  };

  GSFN.hasClassName = function(element, className) {
    var elementClassName = element.className;

    return (elementClassName.length > 0 && (elementClassName == className ||
      new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
  };

  GSFN.addClassName = function(element, className) {
    if (!GSFN.hasClassName(element, className))
      element.className += (element.className ? ' ' : '') + className;
    return element;
  };

  GSFN.removeClassName = function(element, className) {
    var newClass = GSFN.strip(element.className.replace(new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' '));
    element.className = newClass;
    return element;
  };

  GSFN.strip = function(string) {
    return string.replace(/^\s+/, '').replace(/\s+$/, '');
  };
  
  GSFN.add_css = function(css_content) {
    var head = document.getElementsByTagName('head')[0];
    var style = document.createElement('style');
    style.type = 'text/css';
    
    if(style.styleSheet) {
      style.styleSheet.cssText = css_content;
    } else {
      rules = document.createTextNode(css_content);
      style.appendChild(rules);
    }
    head.appendChild(style);
  }

  GSFN.initialized = true;
}

GSFN.feedback_widget = function() {
  var options = {};
  options.display = "overlay";  
  options.company = "celebful";
  options.placement = "left";
  options.color = "#222";
  options.style = "idea";

  this.options = options;
  this.is_ssl = ("https:" == document.location.protocol);
  
  if(!this.options.display){ this.options.display = "overlay";}
  
  if(this.is_ssl) {
    this.feedback_base_url = this.local_ssl_base_url;
    this.asset_base_url = this.s3_ssl_base_url;
  } else {
    this.feedback_base_url = this.local_base_url;
    this.asset_base_url = this.s3_base_url;
  }
  
  if(this.options.local_assets == true) {
    this.asset_base_url = this.feedback_base_url;  
  }

  var disable_tagging = this.options.auto_tag == false;

  query_string_obj = [];
  
  if(!disable_tagging){
    if(this.options.product){ 
      query_string_obj.push("product=" + encodeURIComponent(this.options.product));
    }
  
    if(this.options.tag){
      query_string_obj.push("tag=" + encodeURIComponent(this.options.tag));
    }
  
    if(this.options.user_defined_code){ 
      query_string_obj.push("user_defined_code=" + encodeURIComponent(this.options.user_defined_code));
    }
  }
  
  if(this.options.display){ 
    query_string_obj.push("display=" + encodeURIComponent(this.options.display));
  }
  
  if(this.options.style){ 
    query_string_obj.push("style=" + encodeURIComponent(this.options.style));
  }
  
  if(this.options.popular_topics){ 
    query_string_obj.push("popular_topics=" + encodeURIComponent(this.options.popular_topics));
  }

  if(this.options.limit){
    query_string_obj.push("limit=" + encodeURIComponent(this.options.limit));
  }
  
  if(this.options.problem){ 
    query_string_obj.push("problem=" + encodeURIComponent(this.options.problem));
  }
    
  if(this.options.powered_by){ 
    query_string_obj.push("powered_by=" + encodeURIComponent(this.options.powered_by));
  }
  
  if(this.options.custom_css){
    query_string_obj.push("custom_css=" + encodeURIComponent(this.options.custom_css));
  }
  
  if(this.options.auto_tag == false){
    query_string_obj.push("auto_tag=" + encodeURIComponent(this.options.auto_tag));
  }
  
  if(this.options.interstitial) {
    query_string_obj.push("interstitial=" + encodeURIComponent(this.options.interstitial));
  }
  
  if(this.options.community_base_url) {
    query_string_obj.push("community_base_url=" + encodeURIComponent(this.options.community_base_url));
  }
  
  query_string = "?" + query_string_obj.join("&");

  this.feedback_url = this.feedback_base_url + "/" + this.options.company + "/feedback/topics/new" + query_string;
  
  this.options = options ? options : {};
  this.options.placement = this.options.placement ? this.options.placement : 'left';
  this.options.color = this.options.color ? this.options.color : '#222';

  if(this.options.display == 'overlay') {
    this.initial_iframe_url = this.empty_url();
    if(!this.options.width)   { this.options.width = "658px"; }
    if(!this.options.height)  { this.options.height = "100%"; }
  } else {
    this.initial_iframe_url = this.feedback_url;
    if(!this.options.width)   { this.options.width = "100%"; }
    if(!this.options.height)  { this.options.height = "500px"; }
  }
  
  this.iframe_html = '<iframe id="fdbk_iframe" allowTransparency="true" scrolling="no" frameborder="0" class="loading"' +
                      ' src="'    + this.initial_iframe_url + '"' +
                      ' width="'  + this.options.width + '"' +
                      ' height="'  + this.options.height + '"' +
                      ' style="width: '  + this.options.width + '; height: '  + this.options.height + ';"></iframe>';
  
  this.tab_html = '<a href="#" id="fdbk_tab" class="fdbk_tab_'+this.options.placement+'" style="background-color:'+this.options.color+'">FEEDBACK</a>';
  this.overlay_html = '<div id="fdbk_overlay" style="display:none">' +
                        '<div id="fdbk_container">' +
                          '<a href="#" id="fdbk_close"></a>' +
                          this.iframe_html + 
                        '</div>' +
                        '<div id="fdbk_screen"></div>' +
                      '</div>';
  
  if(this.options.display == 'overlay') {
	//CSS WAS HERE    
    if(this.options.container) {
      var container_el = GSFN.gId(this.options.container); 
      container_el.innerHTML = this.overlay_html; //this.tab_html +
    } else {
      //document.write(this.tab_html);
      document.write(this.overlay_html);     
    }
    
    var feedback_obj = this;
    GSFN.gId('fdbk_tab').onclick = function() { feedback_obj.show(); return false; }
    GSFN.gId('fdbk_close').onclick = function() { feedback_obj.hide(); return false; }
    GSFN.gId('fdbk_iframe').setAttribute("src", this.empty_url());

  } else {
    if(this.options.container) {
      var container_el = GSFN.gId(this.options.container);
      container_el.innerHTML = this.iframe_html; 
    } else {
      document.write(this.iframe_html);
    }
  }

};

GSFN.feedback_widget.prototype = {
  local_base_url: "http:\/\/getsatisfaction.com",
  local_ssl_base_url: "https:\/\/getsatisfaction.com",
  s3_base_url: "http://s3.amazonaws.com/getsatisfaction.com",
  s3_ssl_base_url: "https://s3.amazonaws.com/getsatisfaction.com",
  
  asset_url: function(asset) {
    return this.asset_base_url + asset;
  },
  
  empty_url : function() {
    return this.asset_url("/images/transparent.gif");
  },
  
  set_position : function() {
    this.scroll_top = document.documentElement.scrollTop || document.body.scrollTop;
    this.scroll_height = document.documentElement.scrollHeight;
    this.client_height = window.innerHeight || document.documentElement.clientHeight;
    
    GSFN.gId('fdbk_screen').style.height = this.scroll_height+"px";
    GSFN.gId('fdbk_container').style.top = this.scroll_top+(this.client_height*0.1)+"px";
  },
  
  show : function() {
	//add css here
	if(!GSFN.loadedcss){
	  raw_css = "#fdbk_overlay {\n  width: 100%;\n  height: 100%;\n  top: 0;\n  left: 0;\n  z-index: 1000000;\n  position: absolute; }\n\n#fdbk_screen {\n  top: 0;\n  left: 0;\n  z-index: 1;\n  width: 100%;\n  position: absolute;\n  background-color: #000;\n  opacity: 0.45;\n  -moz-opacity: 0.45;\n  filter: alpha(opacity=45); }\n\n#fdbk_container {\n  width: 680px;\n  height: 640px;\n  margin: 0 auto;\n  z-index: 2;\n  position: relative; }\n  #fdbk_container iframe {\n    width: 658px;\n    height: 100%;\n    margin: 20px;\n    background: transparent; }\n  #fdbk_container iframe.loading {\n    background: transparent url(https:\/\/s3.amazonaws.com\/getsatisfaction.com\/images\/fb_loading.png) no-repeat; }\n\n\na#fdbk_close {\n  position: absolute;\n  cursor: pointer;\n  outline: none;\n  top: 0;\n  left: 0;\n  z-index: 4;\n  width: 42px;\n  height: 42px;\n  overflow: hidden;\n  background-image: url(https:\/\/s3.amazonaws.com\/getsatisfaction.com\/images\/feedback-close.png);\n  _background: none;\n  _filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='https:\/\/s3.amazonaws.com\/getsatisfaction.com\/images\/feedback-close.png', sizingMethod='crop'); }\n  a#fdbk_close:hover {\n    background-position: -42px 0; }\n\n.feedback_tab_on embed, .feedback_tab_on select, .feedback_tab_on object {\n  visibility: hidden; }\n";
	  replacer_regex = new RegExp(this.s3_ssl_base_url, "g");
      translated_css = raw_css.replace(replacer_regex, this.asset_base_url);
      GSFN.add_css(translated_css);
	  GSFN.loadedcss = true;
	}
  
	//
    GSFN.gId('fdbk_iframe').setAttribute("src", this.feedback_url);
    if (GSFN.gId('fdbk_iframe').addEventListener) {
      GSFN.gId('fdbk_iframe').addEventListener("load", this.loaded, false);
    } else if (GSFN.gId('fdbk_iframe').attachEvent) {
      GSFN.gId('fdbk_iframe').attachEvent("onload", this.loaded);
    }
    this.set_position();

    GSFN.addClassName(document.getElementsByTagName('html')[0], 'feedback_tab_on');
    GSFN.gId('fdbk_overlay').style.display = "block";
  },
  
  hide : function() {
    if (GSFN.gId('fdbk_iframe').addEventListener) {
      GSFN.gId('fdbk_iframe').removeEventListener("load", this.loaded, false);
    } else if (GSFN.gId('fdbk_iframe').attachEvent) {
      GSFN.gId('fdbk_iframe').detachEvent("onload", this.loaded);
    }
    
    GSFN.gId('fdbk_overlay').style.display = "none";
    GSFN.gId('fdbk_iframe').setAttribute("src", this.empty_url());
    GSFN.gId('fdbk_iframe').className = "loading";

    GSFN.removeClassName(document.getElementsByTagName('html')[0], 'feedback_tab_on');
  },
  
  loaded : function() {
    GSFN.gId('fdbk_iframe').className = "loaded";
  }
}


/* IE PNG FIX */
// IE5.5+ PNG Alpha Fix v2.0 Alpha: Background Tiling Support
// (c) 2008-2009 Angus Turnbull http://www.twinhelix.com

// This is licensed under the GNU LGPL, version 2.1 or later.
// For details, see: http://creativecommons.org/licenses/LGPL/2.1/

var IEPNGFix = window.IEPNGFix || {};

IEPNGFix.tileBG = function(elm, pngSrc, ready) {
	// Params: A reference to a DOM element, the PNG src file pathname, and a
	// hidden "ready-to-run" passed when called back after image preloading.

	var data = this.data[elm.uniqueID],
		elmW = Math.max(elm.clientWidth, elm.scrollWidth),
		elmH = Math.max(elm.clientHeight, elm.scrollHeight),
		bgX = elm.currentStyle.backgroundPositionX,
		bgY = elm.currentStyle.backgroundPositionY,
		bgR = elm.currentStyle.backgroundRepeat;

	// Cache of DIVs created per element, and image preloader/data.
	if (!data.tiles) {
		data.tiles = {
			elm: elm,
			src: '',
			cache: [],
			img: new Image(),
			old: {}
		};
	}
	var tiles = data.tiles,
		pngW = tiles.img.width,
		pngH = tiles.img.height;

	if (pngSrc) {
		if (!ready && pngSrc != tiles.src) {
			// New image? Preload it with a callback to detect dimensions.
			tiles.img.onload = function() {
				this.onload = null;
				IEPNGFix.tileBG(elm, pngSrc, 1);
			};
			return tiles.img.src = pngSrc;
		}
	} else {
		// No image?
		if (tiles.src) ready = 1;
		pngW = pngH = 0;
	}
	tiles.src = pngSrc;

	if (!ready && elmW == tiles.old.w && elmH == tiles.old.h &&
		bgX == tiles.old.x && bgY == tiles.old.y && bgR == tiles.old.r) {
		return;
	}

	// Convert English and percentage positions to pixels.
	var pos = {
			top: '0%',
			left: '0%',
			center: '50%',
			bottom: '100%',
			right: '100%'
		},
		x,
		y,
		pc;
	x = pos[bgX] || bgX;
	y = pos[bgY] || bgY;
	if (pc = x.match(/(\d+)%/)) {
		x = Math.round((elmW - pngW) * (parseInt(pc[1]) / 100));
	}
	if (pc = y.match(/(\d+)%/)) {
		y = Math.round((elmH - pngH) * (parseInt(pc[1]) / 100));
	}
	x = parseInt(x);
	y = parseInt(y);

	// Handle backgroundRepeat.
	var repeatX = { 'repeat': 1, 'repeat-x': 1 }[bgR],
		repeatY = { 'repeat': 1, 'repeat-y': 1 }[bgR];
	if (repeatX) {
		x %= pngW;
		if (x > 0) x -= pngW;
	}
	if (repeatY) {
		y %= pngH;
		if (y > 0) y -= pngH;
	}

	// Go!
	this.hook.enabled = 0;
	if (!({ relative: 1, absolute: 1 }[elm.currentStyle.position])) {
		elm.style.position = 'relative';
	}
	var count = 0,
		xPos,
		maxX = repeatX ? elmW : x + 0.1,
		yPos,
		maxY = repeatY ? elmH : y + 0.1,
		d,
		s,
		isNew;
	if (pngW && pngH) {
		for (xPos = x; xPos < maxX; xPos += pngW) {
			for (yPos = y; yPos < maxY; yPos += pngH) {
				isNew = 0;
				if (!tiles.cache[count]) {
					tiles.cache[count] = document.createElement('div');
					isNew = 1;
				}
				var clipR = Math.max(0, xPos + pngW > elmW ? elmW - xPos : pngW),
					clipB = Math.max(0, yPos + pngH > elmH ? elmH - yPos : pngH);
				d = tiles.cache[count];
				s = d.style;
				s.behavior = 'none';
				s.left = (xPos - parseInt(elm.currentStyle.paddingLeft)) + 'px';
				s.top = yPos + 'px';
				s.width = clipR + 'px';
				s.height = clipB + 'px';
				s.clip = 'rect(' +
					(yPos < 0 ? 0 - yPos : 0) + 'px,' +
					clipR + 'px,' +
					clipB + 'px,' +
					(xPos < 0 ? 0 - xPos : 0) + 'px)';
				s.display = 'block';
				if (isNew) {
					s.position = 'absolute';
					s.zIndex = -999;
					if (elm.firstChild) {
						elm.insertBefore(d, elm.firstChild);
					} else {
						elm.appendChild(d);
					}
				}
				this.fix(d, pngSrc, 0);
				count++;
			}
		}
	}
	while (count < tiles.cache.length) {
		this.fix(tiles.cache[count], '', 0);
		tiles.cache[count++].style.display = 'none';
	}

	this.hook.enabled = 1;

	// Cache so updates are infrequent.
	tiles.old = {
		w: elmW,
		h: elmH,
		x: bgX,
		y: bgY,
		r: bgR
	};
};


IEPNGFix.update = function() {
	// Update all PNG backgrounds.
	for (var i in IEPNGFix.data) {
		var t = IEPNGFix.data[i].tiles;
		if (t && t.elm && t.src) {
			IEPNGFix.tileBG(t.elm, t.src);
		}
	}
};
IEPNGFix.update.timer = 0;

if (window.attachEvent && !window.opera) {
	window.attachEvent('onresize', function() {
		clearTimeout(IEPNGFix.update.timer);
		IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
	});
}