/*!
 * JSizes - JQuery plugin v0.33
 *
 * Licensed under the revised BSD License.
 * Copyright 2008-2010 Bram Stein
 * All rights reserved.
 */
/*global jQuery*/
(function ($) {
	var num = function (value) {
			return parseInt(value, 10) || 0;
		};

	/**
	 * Sets or gets the values for min-width, min-height, max-width
	 * and max-height.
	 */
	$.each(['min', 'max'], function (i, name) {
		$.fn[name + 'Size'] = function (value) {
			var width, height;
			if (value) {
				if (value.width !== undefined) {
					this.css(name + '-width', value.width);
				}
				if (value.height !== undefined) {
					this.css(name + '-height', value.height);
				}
				return this;
			}
			else {
				width = this.css(name + '-width');
				height = this.css(name + '-height');
				// Apparently:
				//  * Opera returns -1px instead of none
				//  * IE6 returns undefined instead of none
				return {'width': (name === 'max' && (width === undefined || width === 'none' || num(width) === -1) && Number.MAX_VALUE) || num(width), 
						'height': (name === 'max' && (height === undefined || height === 'none' || num(height) === -1) && Number.MAX_VALUE) || num(height)};
			}
		};
	});

	/**
	 * Returns whether or not an element is visible.
	 */
	$.fn.isVisible = function () {
		return this.is(':visible');
	};

	/**
	 * Sets or gets the values for border, margin and padding.
	 */
	$.each(['border', 'margin', 'padding'], function (i, name) {
		$.fn[name] = function (value) {
			if (value) {
				if (value.top !== undefined) {
					this.css(name + '-top' + (name === 'border' ? '-width' : ''), value.top);
				}
				if (value.bottom !== undefined) {
					this.css(name + '-bottom' + (name === 'border' ? '-width' : ''), value.bottom);
				}
				if (value.left !== undefined) {
					this.css(name + '-left' + (name === 'border' ? '-width' : ''), value.left);
				}
				if (value.right !== undefined) {
					this.css(name + '-right' + (name === 'border' ? '-width' : ''), value.right);
				}
				return this;
			}
			else {
				return {top: num(this.css(name + '-top' + (name === 'border' ? '-width' : ''))),
						bottom: num(this.css(name + '-bottom' + (name === 'border' ? '-width' : ''))),
						left: num(this.css(name + '-left' + (name === 'border' ? '-width' : ''))),
						right: num(this.css(name + '-right' + (name === 'border' ? '-width' : '')))};
			}
		};
	});
})(jQuery);


/**************************************************************************************************
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

function readCookie(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;
}
/*************************************************************************************************
Jquery Cookie*/

(function($) {
  
  // Naive method of yanking the querystring portion from a string (just splits on the first '?', if present).
  function extractQuery(string) {
    if(string.indexOf('?') >= 0) {
      return string.split('?')[1];
    } else {
      return string;
    }
  };
  
  // Returns the JavaScript value of a querystring parameter.
  // Decodes the string & coerces it to the appropriate JavaScript type.
  // Examples:
  //    'Coffee%20and%20milk' => 'Coffee and milk'
  //    'true' => true
  //    '21' => 21
  function parseValue(value) {
    value = decodeURIComponent(value);
    try {
      return JSON.parse(value);
    } catch(e) {
      return value;
    }
  }
  
  // Takes a URL (or fragment) and parses the querystring portion into an object.
  // Returns an empty object if there is no querystring.
  function parse(url) {
    var params = {},
        query = extractQuery(url);

    if(!query) {
      return params;
    }
    
    $.each(query.split('&'), function(idx, pair) {
      pair = pair.split('=');
      params[pair[0]] = parseValue(pair[1] || '');
    });

    return params;
  };
  
  // Takes an object and converts it to a URL fragment suitable for use as a querystring.
  function serialize(params) {
    var pairs = [], currentKey, currentValue;
    
    for(key in params) {
      if(params.hasOwnProperty(key)) {
        currentKey = key;
        currentValue = params[key];
        
        if(typeof currentValue === 'object') {
          for(subKey in currentValue) {
            if(currentValue.hasOwnProperty(subKey)) {
              // If subKey is an integer, we have an array. In that case, use `person[]` instead of `person[0]`.
              pairs.push(currentKey + '[' + (isNaN(subKey, 10) ? subKey : '') + ']=' + encodeURIComponent(currentValue[subKey])); 
            }
          }
        } else {
          pairs.push(currentKey + '=' + encodeURIComponent(currentValue)); 
        }
      }
    }
    
    return pairs.join("&");
  };
  
  // Public interface.
  $.querystring = function(param) {
    if(typeof param === 'string') {
      return parse(param);
    } else {
      return serialize(param);
    }
  };
  
  // Adds a method to jQuery objects to get & querystring.
  //  $('#my_link').querystring(); // => {name: "Joe", job: "Plumber"}
  //  $('#my_link').querystring({name: 'Jack'}); // => Appends `?name=Jack` to href.
  $.fn.querystring = function() {
    var elm = $(this),
        existingData,
        newData = arguments[0] || {},
        clearExisting = arguments[1] || false;
    
    if(!elm.attr('href')) {
      return;
    }
    
    existingData = parse(elm.attr('href'));
    
    // Get the querystring & bail.
    if(arguments.length === 0) {
      return existingData;
    }
    
    // Set the querystring.
    if(clearExisting) {
      existingData = newData;
    } else {
      $.extend(existingData, newData); 
    }
    elm.attr('href', elm.attr('href').split("?")[0] + "?" + serialize(existingData));
    return elm;
    
  };
  
})(jQuery);

/*************************************************************************************************/

/*-------------------------------------------------------------------- 
 * JQuery Plugin: "EqualHeights"
 * by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
 *
 * Copyright (c) 2008 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Description: Compares the heights or widths of the top-level children of a provided element 
 		and sets their min-height to the tallest height (or width to widest width). Sets in em units 
 		by default if pxToEm() method is available.
 * Dependencies: jQuery library, pxToEm method	(article: 
		http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)							  
 * Usage Example: $(element).equalHeights();
  		Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
 * Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/

$.fn.equalHeightsImproved = function(px, inner) {
	$(this).each(function(){
		var currentTallest = 0;
		var matchingElements = $(this).children();
		if (inner) {
			matchingElements = $(this).find(inner);
		}
		matchingElements.each(function(i){
			if ($(this).height() > currentTallest) { currentTallest = $(this).height();
			}
		});
		//if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
		// for ie6, set height since min-height isn't supported
		if ($.browser.msie && $.browser.version == 6.0) { matchingElements.css({'height': currentTallest}); }
		matchingElements.css({'min-height': currentTallest}); 
	});
	return this;
};

/*************************************************************************************************
Slicker Javascript */
$(document).ready(function() {
 // shows and hides and toggles the loginbox on click  
  $('#slick-show').click(function() {
    $('#loginbox').show('slow');
    return false;
  });
  $('#slick-hide').click(function() {
    $('#loginbox').hide('fast');
    return false;
  });
  $('#slick-toggle').click(function() {
    $('#loginbox').toggle(400);
    return false;
  });

 // slides down, up, and toggle the loginbox on click    
  $('#slick-down').click(function() {
    $('#loginbox').slideDown('slow');
    return false;
  });
  $('#slick-up').click(function() {
    $('#loginbox').slideUp('fast');
    return false;
  });
  $('#slick-slidetoggle').click(function() {
    $('#loginbox').slideToggle(400);
    return false;
  });
});
/*************************************************************************************************/



/************************ Check, get, and Set Cookie, then change URLs ***************************/			
var qs = $.querystring(window.location.href);

if (qs['r']){
	$.cookie('opriusAffiliate', qs['r'], { expires: 180 });
}
if (qs['a']){
	$.cookie('opriusAffiliate', qs['a'], { expires: 180 });
}
if (qs['ref']){
	$.cookie('opriusAffiliate', qs['ref'], { expires: 180 });
}
if (qs['l']){
	window.location.href = qs['l'];
}

$(function(){ 
	var refCode = $.cookie('opriusAffiliate');
	if (refCode) {
		$('.signUp').attr("href", "https://app.oprius.com/signup?Affiliate="+refCode)
	}
});


/******************************** Vertical Align Function *******************************************/
(function ($) {
// VERTICALLY ALIGN FUNCTION
$.fn.vAlign = function() {
	return this.each(function(i){
	var ah = $(this).height();
	var ph = $(this).parent().height();
	var mh = Math.ceil((ph-ah) / 2);
	$(this).css('margin-top', mh);
	});
};
})(jQuery);

(function ($) {
// VERTICALLY BOTTOM ALIGN FUNCTION
$.fn.bAlign = function() {
	return this.each(function(i){
		/*(var ah = $(this).height();
		var ph = $(this).parent().innerHeight() - $(this).parent().padding()['top'] - $(this).parent().padding()['bottom'];
		var current_position = $(this).position()['top']-$(this).parent().padding()['top'];
		var mh = Math.ceil((ph-current_position-ah));
		$(this).css('position', 'relative');
		$(this).css('top', mh + 'px');*/
		/*$(this).css('position', 'absolute');
		$(this).css('bottom', '10px');*/
	});
};
})(jQuery);

(function ($) {
// FULL WIDTH FOR BUTTONS
$.fn.fullWidth = function() {
	return this.each(function(i){
		var pw = $(this).parent().outerWidth();
		//calculate padding and margin
		var surroundings = $(this).padding().left+$(this).padding().right+$(this).border().left+$(this).border().right;
		$(this).css('width', pw-surroundings);
	});
};
})(jQuery);

//Browser Check Cookie

browserCookie = function(){
	$.cookie('browser_ignore', 'ignored', { expires: 180 });
};
//Browser Check
$(document).ready(function(){

	if($.browser.msie)
	{
		if($.browser.version<8)
		{
			if (document.location.href.search("old_browser.html")==-1){
				if ($.cookie('browser_ignore')!="ignored"){
					window.location.href = "/old_browser.html";
				}
			}
		}
	}
});

/*************************************************************************************************
Random Image Javascript */

(function($){
	
	$.randomImage = {
		defaults: {
			
			//you can change these defaults to your own preferences.
			path: '/testimonial_images/', //change this to the path of your images
			myImages: [["wagner_small.png", "Leah", "wagner", "she"], ["murray_small.jpg", "Jason", "murray", "he"], ["figueroa_small.jpg", "Barbie", "figueroa", "she"]]
		}			
	}
	
	$.fn.extend({
			randomImage:function(config) {
				
				var config = $.extend({}, $.randomImage.defaults, config); 
				
				 return this.each(function() {
						
						var imageNames = config.myImages;
						
						//get size of array, randomize a number from this
						// use this number as the array index

						var imageNamesSize = imageNames.length;

						var lotteryNumber = Math.floor(Math.random()*imageNamesSize);

						var winnerImage = imageNames[lotteryNumber];

						var fullPath = config.path + winnerImage[0];
						
						
						//put this image into DOM at class of randomImage
						// alt tag will be image filename.
						$(this).find('.r1').text(winnerImage[1]+' Loves Us');
						$(this).find('.r2').text('Find out what '+winnerImage[1]+' loves about Oprius and how '+winnerImage[3]+' uses it.');
						$(this).find('img').attr( {
										src: fullPath,
										alt: winnerImage[1]+' '+winnerImage[2]
									});
						$(this).find('a').attr( {
										href: "/testimonials/testimonial-"+winnerImage[2]+".html",
										'class': "blueButton"
									});
				
						
				});	
			}
			
	});
	
	
	
})(jQuery);

