		$(document).ready(function(){
			$('div.section').hover(
				function(){
					$(this).css({'background-color' : 'B3D9FF'});
					$(this).find('.help').fadeIn(400);
				},
				function(){
					$(this).css({'background-color' : 'FFFFFF'});
					$(this).find('.help').fadeOut(100);
				}
			);
			
			var oCSource = new AutoSuggestControl(document.getElementById("utm_source"), new SourceSuggestions()); 
			var oCMedium = new AutoSuggestControl(document.getElementById("utm_medium"), new MediumSuggestions()); 
			var oCContent = new AutoSuggestControl(document.getElementById("utm_content"), new ContentSuggestions()); 
			
		});



		BitlyCB.getData = function ()
		{
			var data = {};
			data.params = new Array;
			
			data.destUrl = document.getElementById("website").value;
			
			data.params['utm_campaign'] = document.getElementById("utm_campaign").value;
			data.params['utm_source'] = document.getElementById("utm_source").value;
			data.params['utm_medium'] = document.getElementById("utm_medium").value;
			data.params['utm_term'] = document.getElementById("utm_term").value;
			data.params['utm_content'] = document.getElementById("utm_content").value;
			
			data.convAttr = document.getElementById("conv_attr").checked ? 1 : 0;
			data.paramSep = document.getElementById("param_sep_1").checked ? '?' : '#';
			data.shortener = document.getElementsByName("url_shortener");
			
			for (i=0;i<data.shortener.length;i++)
				if (data.shortener[i].checked)
				{
					data.shortener = data.shortener[i].value;
					break;
				}
			
			return data;
		}
		
		BitlyCB.compileUrl = function ()
		{
			var data = BitlyCB.getData();
			
			var error = [];
			if (data.destUrl == '')
				error.push('Fill destanation url field with correct value!');
			if (data.params['utm_campaign'] == '')
				error.push('Campaign Name can\'t be empty');
				
			if (data.params['utm_source'] == '')
				error.push('Campaign Source can\'t be empty');

			if (data.params['utm_medium'] == '')
				error.push('Campaign Medium can\'t be empty');
			
			if (error.length != 0)
			{
				alert(error.join("\n"));
				return false;
			}
			
			var url = '';
			var pstr = [];
			for (pname in data.params)
				pstr.push(pname + '=' + data.params[pname]);
			pstr = pstr.join('&');
			
			if (data.convAttr == 1)
				pstr += '&utm_nooverride=1';
			
			var pattern = "^(([^:/\\?#]+):)?(//(([^:/\\?#]*)(?::([^/\\?#]*))?))?([^\\?#]*)(\\?([^#]*))?(#(.*))?$";
			//var pattern = "(\\?([^#]*))?(#(.*))?$";
			var rx = new RegExp(pattern);
			var parts = rx.exec(data.destUrl);
			
			data.url = {};
			data.url.href = parts[0] || "";
			data.url.protocol = parts[1] || "";
			data.url.host = parts[4] || "";
			data.url.hostname = parts[5] || "";
			data.url.port = parts[6] || "";
			data.url.pathname = parts[7] || "/";
			data.url.search = parts[8] || "";
			data.url.hash = parts[10] || "";
			
			if (data.url.search == '')
				pstr = data.paramSep + pstr;
			else
				pstr = data.paramSep + pstr;
				
			url = data.url.protocol + '//' + data.url.host + data.url.pathname + data.url.search + pstr + data.url.hash 
			
			return url;
		}

		BitlyClient.addPageLoadEvent(function(){			
			document.getElementById('shorten-url-btn').onclick = function(){
				
				if (document.getElementsByName('url_shortener')[0].value == 'bit.ly')
				{
					BitlyCB.myShortenCallback = function(data) {
						var result;
						for (var r in data.results) {
							result = data.results[r];
							result['longUrl'] = r;
							break;
						}
						document.getElementById("short_res").value = result['shortUrl'];
					}
					BitlyClient.shorten(document.getElementById('result').value, 'BitlyCB.myShortenCallback');
				}
			
				if (document.getElementsByName('url_shortener')[0].value == 'php')
				{
					document.getElementById("short_res").value = document.location + '?url=' + document.getElementById('result').value;
				}
				
			}

			document.getElementById('build-url-btn').onclick = function(){
				var url = BitlyCB.compileUrl()
				if (url != false)
					document.getElementById("result").value = url;
			}
		});
		
		
function AutoSuggestControl(oTextbox, oProvider) {
    this.provider = oProvider;
    this.textbox = oTextbox;
	this.init();
}

AutoSuggestControl.prototype.selectRange = function (iStart, iLength) {
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange(); 
        oRange.moveStart("character", iStart); 
        oRange.moveEnd("character", iLength - this.textbox.value.length); 
        oRange.select();
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iLength);
    }

    this.textbox.focus(); 
};

AutoSuggestControl.prototype.typeAhead = function (sSuggestion) {
    if (this.textbox.createTextRange || this.textbox.setSelectionRange) {
        var iLen = this.textbox.value.length; 
        this.textbox.value = sSuggestion; 
        this.selectRange(iLen, sSuggestion.length);
    }
};

AutoSuggestControl.prototype.autosuggest = function (aSuggestions) {

    if (aSuggestions.length > 0) {
        this.typeAhead(aSuggestions[0]);
    }
};

AutoSuggestControl.prototype.handleKeyUp = function (oEvent) {
     var iKeyCode = oEvent.keyCode;

     if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode <= 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
        //ignore
    } else {
        this.provider.requestSuggestions(this);
    }
};

AutoSuggestControl.prototype.init = function () {
    var oThis = this;
    this.textbox.onkeyup = function (oEvent) {
        if (!oEvent) {
            oEvent = window.event;
        }
        oThis.handleKeyUp(oEvent);
    };
};


function SourceSuggestions() {
    this.sources = [
        "bing", "yahoo", "facebook", "myspace", "twitter", "youtube", "linkedin", 
		"adbrite", "newsletter", "linkshare", "commission_junction", "affiliate_window", "buyat", "tradedoubler", 
		"tv", "print", "radio"
    ];
}

SourceSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl) {
    var aSuggestions = [];
    var sTextboxValue = oAutoSuggestControl.textbox.value;
	if (sTextboxValue.length > 0){
        for (var i=0; i < this.sources.length; i++) { 
            if (this.sources[i].indexOf(sTextboxValue) == 0) {
                aSuggestions.push(this.sources[i]);
            } 
        } 
        oAutoSuggestControl.autosuggest(aSuggestions);
		if (aSuggestions[0] == 'yahoo')
		{
			document.getElementById('utm_term').value = '{OVKEY}';
			document.getElementById('utm_content').value = '{OVADID}';
		}
		if (aSuggestions[0] == 'bing')
		{
			document.getElementById('utm_term').value = '{keyword}';
			document.getElementById('utm_content').value = '{AdID}';
		}
			
		if (in_array(aSuggestions[0] , ["bing", "yahoo"]))
			document.getElementById('utm_medium').value = 'cpc';
		if (in_array(aSuggestions[0] , ["facebook", "myspace", "twitter", "youtube", "linkedin"]))
		{
			document.getElementById('utm_medium').value = 'social';
			document.getElementById('utm_content').value = 'web_app';
		}
		if (in_array(aSuggestions[0] , ["newsletter"]))
			document.getElementById('utm_medium').value = 'email';	
		if (in_array(aSuggestions[0] , ["linkshare", "commission_junction", "affiliate_window", "buyat", "tradedoubler"]))
			document.getElementById('utm_medium').value = 'affiliates';	
		if (in_array(aSuggestions[0] , ["tv", "print", "radio"]))
			document.getElementById('utm_medium').value = 'offline';		
    } 
};

//
function MediumSuggestions() {
    this.medium = [
        "cpc", "social", "display_ad", "text_ad", "video_ad", "affiliates", "email", 
		"offline"
    ];
}
MediumSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl) {
    var aSuggestions = [];
    var sTextboxValue = oAutoSuggestControl.textbox.value;
	if (sTextboxValue.length > 0){
        for (var i=0; i < this.medium.length; i++) { 
            if (this.medium[i].indexOf(sTextboxValue) == 0) {
                aSuggestions.push(this.medium[i]);
            } 
        } 
        oAutoSuggestControl.autosuggest(aSuggestions);
    } 
};

//
function ContentSuggestions() {
    this.content = [
        "{OVADID}", "{AdID}", "web_app", "widget"
    ];
}
ContentSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl) {
    var aSuggestions = [];
    var sTextboxValue = oAutoSuggestControl.textbox.value;
	if (sTextboxValue.length > 0){
        for (var i=0; i < this.content.length; i++) { 
            if (this.content[i].indexOf(sTextboxValue) == 0) {
                aSuggestions.push(this.content[i]);
            } 
        } 
        oAutoSuggestControl.autosuggest(aSuggestions);
    } 
};

function in_array(needle, haystack, strict) {
     var found = false, key, strict = !!strict;
 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
 
    return found;
}
