var si= {}; 

si.si_cdn_url = '';
si.settings = {};
si.view = {};
si.view.theme = 'si-minimal';
si.browser = '';
si.currency_code = 'USD';
si.currency_symbol = '$';
si.current_url = window.location.href;
si.message_target = '';
si.menuDelayHide = 0;

si.include = function(script) {
	document.write("<script type='text/javascript' src='" + script + "'></script>");
};

si.init = function() {
	si.browser = si.get_browser();
	si.brands.name = si.settings.aliases.brands;
	si.search.obj = si.search.data;
	
	if (si.settings.facebook.enabled) {
		si.check_facebook_settings();
	}
};

si.load = function(url) {
	si.si_cdn_url = url;
	// load core si libraries
	var files = ['assets', 'brands', 'cart', 'categories', 'checkout', 'collections', 'content', 'facebook', 'paginate', 'products', 'products_gallery', 'search', 'store', 'tags', 'users'];
	for (var i = 0; i < files.length; i++){
		si.include(url + '/js/core/si.' + files[i] + '.js');
	}
	
};

/*browser detection*/
si.get_browser = function($) {
	var userAgent = navigator.userAgent.toLowerCase();
	var browser = {
		userAgent: userAgent,
		version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
		safari: /webkit/.test( userAgent ),
		chrome: /chrome/.test( userAgent ),
		opera: /opera/.test( userAgent ),
		msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
		mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
	};
	
	return browser;
};

/*generic load function*/
si.loadContent = function(loc, id) {
	var $id = $(id);
	$.get(loc, function(data) {
			$id.html(data);
			$id.fadeIn();
		}
	);
};



si.init_popup = function(popup_link) {
	var popup_data = popup_link.attr('href');
	var popup_id = popup_link.attr('rel');
	si.popup(popup_data, popup_id);
};

si.popup = function(popup_data, popup_id){
	si.close_popup(); //close existing popups
	var data_target = "#" + popup_id;
	var str = "";
	
	str += "<div class='SIoverlay' style='position:fixed;width:100%;height:100%;top:0;left:0;z-index:1500;'>" +
	"</div><div class='SIpopup' id='" + popup_id + "' style='position:fixed;z-index:1501;display:none;left:0;'></div>";
	
	$("body").prepend(str);
	
	//load content into popup
	si.loadContent(popup_data, data_target);

	//close popups when overlay or close button is clicked
	$(".SIoverlay").click(function(){
		si.close_popup();
	});
	
	//make draggable
	$(data_target).draggable({ handle: 'h1' });
};


si.close_popup = function() {
	$("div.SIoverlay, div.SIpopup, #SIiframe").remove();
	si.popupOpen = false; // may not be necessary
}

/*position popup function*/
si.positionPopup = function(){
	var initialHeight = $("div.SIpopup").height();
	var resizeWrapperHeight = $("#resizeWrapper").height();
	var nonResizeHeight = initialHeight - resizeWrapperHeight;
	
	if ( initialHeight > $(window).height()-100){
		$("#resizeWrapper").height($(window).height() - (100 + nonResizeHeight));
	}
	
	var heightOffset = ($(window).height() - $("div.SIpopup").height())/2;
    
    //KLUDGE: set height manually for inside FB iframe because it doesn't resize properly at the moment
    if(si.settings.facebook.in_iframe) {
        heightOffset = 200;
    }
    
	var widthOffset = ($("div.SIpopup").width()/2) + 20;
	$("div.SIpopup").css({marginLeft:-widthOffset, left:"50%", top: heightOffset-25});
}


/*pop up violent message*/
si.violent_message = function(message){
	si.close_popup(); //close existing popups
	var str = '';
	
	str += '<div class="SIoverlay" style="position:fixed;width:100%;height:100%;top:0;left:0;z-index:1500;">' + 
	'</div><div class="SIpopup violentMessage" style="position:fixed;z-index:1501;display:none;left:0;width:360px;">' +
	'<h1>Sorry About This <a href="#" class="close invisiText" onclick="si.close_popup();return false;">close</a></h1>' +
	'<p>' + message + '</p>' +
	'<div class="buttonWrapper"><a href="#" onclick="si.close_popup();return false;" class="button">Close</a></div>' +
	'</div>';
	
	
	$("body").prepend(str);

	//close popups when overlay or close button is clicked
	$(".SIoverlay").click(function(){
		si.close_popup();
	});
	
	si.positionPopup();
	
	$("div.SIpopup").fadeIn();
};


/* set unfilled out fields with hints to blank */
si.clear_hints = function(form) {
	form.find('input').each(function() {
		if ($(this).val() == $(this).attr("title")) {
			$(this).val('');
		}
	});
};


/*sitewide messages*/ 
si.message = function(message) {
	message = message || '';
	if (si.message_target.length > 0) {
		si.message_target.html(message).fadeIn();
	} else {
		alert("You have removed the call to the siMessage() jquery plugin or removed the HTML element it targets, please put it back so we can tell you important things!");
	}
};

si.message_close = function() {
	if (si.message_target.length > 0) {
		si.message_target.html("").fadeOut();
	} else {
		alert("You have removed the call to the siMessage() jquery plugin or removed the HTML element it targets, please put it back so we can tell you important things!");
	}
}

/*sticky tool functions*/
si.setStickyStatus = function(id) {
	// set foot status TODO: should post to site home controller? should be set_stickyTools
	$.post('/' + si.settings.routes.store + '/home/set_footer/', { 'id' : id }, function(data){
        if (data.success) {
			si.view.sticky = data.results.status;
			
			// check to see if microcart continue to checkout has been clicked in stickyTools
			if (si.cart.microcart_checkout_link === true) {
				document.location.href = '/cart';
				return;
			}
		}
	}, "json");
};

si.checkStickyStatus = function() {
	// check existing footer state
	if (si.view.sticky !== 0) {
		$(si.view.sticky).addClass("active stickyActive").parent().addClass("active");
	}
};

si.check_facebook_settings = function() {
	if (si.settings.facebook != undefined && document.cookie.length > 0) {
		var str = String(window.location);
		
		// in an iframe and in facebook style set to false
		if (top !== self && si.settings.facebook.in_iframe == false && str.indexOf('fb_xd_fragment') === -1) {
			// reset the facebook in iframe value to true
			$.getJSON('/' + si.settings.routes.store + '/home/set_facebook_iframe/1/?' + Math.floor(Math.random()*9999999+1), function(data) {
				if (data.success) {
					window.location.reload(); // reset the url
				}
			});
		}
		
		// not in an iframe and in facebook style set to true
		if (top === self && si.settings.facebook.in_iframe == true) {
			// reset the facebook in iframe value to false
			$.getJSON('/' + si.settings.routes.store + '/home/set_facebook_iframe/0/?' + Math.floor(Math.random()*9999999+1), function(data) {
				if (data.success) {
					window.location.reload(); // reset the url
				}
			});
		}
	}
};

si.repeat = function(str, i) {
	if (isNaN(i) || i == 0) return "";
	return str + si.repeat(str, i-1);
};

si.to_url = function (str) {
	return str
		.toLowerCase()
		.replace(/ +/g,'-')
		.replace(/[^\w+(\-)]+/g,'')
		;
};

si.strip_html = function(str) {  
	return str
		.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,'')
		;
};

si.url_encode = function(c) {
	var o = '';
	var x = 0;
	c = c.toString();
	var r = /(^[a-zA-Z0-9_.]*)/;
	while (x < c.length) {
		var m = r.exec(c.substr(x));
		if (m != null && m.length > 1 && m[1] != '') {
			o += m[1];
			x += m[1].length;
		} else {
			if (c[x] == ' ') o += '+';
			else {
				var d = c.charCodeAt(x);
				var h = d.toString(16);
				o += '%' + (h.length < 2 ? '0': '') + h.toUpperCase();
			}
			x++;
		}
	}
	return o;
};
	
si.url_decode = function(s) {
	var o = s;
	var binVal, t;
	var r = /(%[^%]{2})/;
	while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
		b = parseInt(m[1].substr(1), 16);
		t = String.fromCharCode(b);
		o = o.replace(m[1], t);
	}
	return o;
};

/* VIEW MARKUP REPLACEMENT */
si.inject_markup = function(prefix, markup, replacements){
	var regex;
	$.each(replacements, function(key, value) { 
		regex = new RegExp('{' + prefix + '_' + key + '}', "g");
		markup = markup.replace(regex, value);
	});
	return markup;
};

si.singularize = function(type) {
	var str = type; // return itself if not found...
	switch(type) {
		case('categories'):
			str = 'category';
		break;
		case('brands'):
			str  = 'brand';
		break;
		case('collections'):
			str = 'collection';
		break;
		case('products'):
			str = 'product';
		break;
	}
	
	return str;
};

si.in_array = function(needle, haystack, argStrict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false

    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
};

si.create_cookie = function(name,value,days) {
	if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
	}
	else {
			var expires = "";
	}

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

si.read_cookie = 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;
};

si.remove_cookie = function(name) {
    si.create_cookie(name,"",-1);
};

