// File: global.js
// Requires: prototype.js

// Class Definition
SearchForm = Class.create();
SearchForm.prototype = {
	form : null,
	bttnSubmit : null,
	eltCurrentMode : null,
	linksMode : null,
	strIdSuffix : null,
	bSetMediaTypeInButton : false,
	bJWidgetSearch : false,

	initialize: function(strIdSuffix, bSetMediaTypeInButton, bJWidgetSearch)
	{
		this.strIdSuffix = strIdSuffix;
		this.bSetMediaTypeInButton = (typeof(bSetMediaTypeInButton) != "undefined" && bSetMediaTypeInButton);
		this.bJWidgetSearch  = (typeof(bJWidgetSearch) != "undefined" && bJWidgetSearch);

		this.form = $("form" + strIdSuffix);

		this.bttnSubmit = $("submit" + strIdSuffix);
		this.eltCurrentMode = $("mode" + strIdSuffix);

		// Get list of search mode links
		var eltContainer = $("groupSearchModeLinks" + strIdSuffix);
		var listLinks = eltContainer.getElementsByTagName("A");
		var urlArr = document.location.href.split("/"); // = ['http:', '', <domain>, <path + querystring>]

		this.linksMode = new Object(); // Assoc Array of mode links
		// set media type based on the search url (if we are in search)
		var i;
		var setSelected = false;
		var urlAction;

		if(!this.bJWidgetSearch){
			urlAction = urlArr[3].split("?")[0];
		}
		else{	// In JWidget, Mode is retrieved from the mode input
			urlAction = this.eltCurrentMode.value;
		}

		for(i = 0; i < listLinks.length; i++){
			var keyMode = listLinks[i].href.split("/")[3];

			this.linksMode[keyMode] = listLinks[i];

			if(listLinks[i].id == urlAction + strIdSuffix){

				var eltText = listLinks[i].getElementsByTagName("SPAN");
				eltText = eltText[0].innerHTML;

				this.setMode(listLinks[i]);
				setSelected = true;

				if(this.bSetMediaTypeInButton){
					this.bttnSubmit.value = this.bttnSubmit.value + " " + urlArr[3];
				}
			}
		}

		// Set Media type based on Media Detail media type
		if(!bJWidgetSearch && !setSelected && urlArr[3] == "mediadetail"){ // Note: Bypass for JWidget
			var queryArr = document.location.href.toQueryParams();
			var mediaType;

			if(queryArr && typeof(mediaType = queryArr["media"]) != "undefined"){
				if(mediaType.indexOf(".pbr") > -1){	// Remix
					mediaType = "videos";
				}
				else if(mediaType.match(/\.flv$/)){ // Video
					mediaType = "videos";
				}
				else{	// Images (default)
					mediaType = "images";
				}

				this.setMode(this.linksMode[mediaType]);
				setSelected = true;
			}
		}

		// Default to image type
		if(!setSelected) {
			var imagesElement = $("images" + strIdSuffix);
			Element.addClassName(imagesElement, "selected");
			this.setMode(imagesElement);
		}
	},
	getMode : function()
	{
		var mode = "";
		if(this.eltCurrentMode){
			mode = this.eltCurrentMode.value;
		}
		return mode;
	},
	setMode : function(eltModeLink)
	{
		if(this.eltCurrentMode && eltModeLink){

			var mode = eltModeLink.href.split("/")[3];

			if(mode.indexOf("?") > -1){
				mode = mode.split("?")[0];
			}

			this.eltCurrentMode.value = mode;

			Element.addClassName(eltModeLink, "selected"); // set the mode link CSS class to selected

			// Don't set the form action and method in JWidget
			if(!this.bJWidgetSearch){
				var action = this.form.action.split("/");

				if(action.pop() == ""){
					action.pop();
				}
				action.push(mode);

				// change the form method based on the id
				if(eltModeLink.id == "websearch" + this.strIdSuffix){
					this.form.method = "get";
				}
				else{
					action.push("");
					this.form.method = "post";
				}

				this.form.action = action.join("/");
			}

			if(this.bSetMediaTypeInButton){
				var textButton = this.bttnSubmit.value.split(" ")[0];
				var textMode = this.linksMode[mode].getElementsByTagName("SPAN")[0].innerHTML;
				this.bttnSubmit.value = textButton + " " + textMode;
			}
		}
	},
	handleModeLinkClick: function(e)
	{
		var elt = Event.findElement(e, "A");

		var i;
		// Remove Selected class from currently
		for(var key in this.linksMode){
			if(Element.hasClassName(this.linksMode[key], "selected")){
				Element.removeClassName(this.linksMode[key], "selected");
			}
		}
		this.setMode(elt);

		Event.stop(e);

		return false;
	},
	handleSubmitClick: function(e)
	{
		var mode = this.getMode();
		if(mode == "websearch"){
			this.form.submit();
		}
		else{
			var query = $("q" + this.strIdSuffix);
			document.location.href = this.form.action + escape(escape(query.value)) + '/';
		}
		return false;
	}
};

// For tracking click events on image codes
function trackCodeClick(evnt) {
	var elt = Event.element(evnt);

	if(elt) {
        var code = elt.value;

        if(code.match(/^http:/)) {
            if(code.indexOf("?") > -1) {
                // Track Share url
                APIRequest.track('image_code_click_SHARE_URL');
            } else {
                // Track Direct url
                APIRequest.track('image_code_click_URL_LINK');
            }
        } else if(code.match(/^<img src=/) || code.match(/^<embed/) || code.match(/^<a href=/)) {
            // Track HTML Url
            APIRequest.track('image_code_click_HTML');
		} else if(code.match(/^\[URL=http:/) || code.match(/^\[IMG\]http:/)) {
            // Track IMG url
            APIRequest.track('image_code_click_IMG');
        }
    }
    return true;
}

// Requires: prototype.js, scriptaculous.js?load=effects

function copyToClipboard(elt) {
	var urlSwf = "/include/swf/_clipboard.swf";
	var strMssgBoxId = "notifyTextCopied";
	var eltNotify = null;

	// Display Notifications
	if((eltNotify = $(strMssgBoxId)) == null){
		// Attach the notification to the DOM
		var eltBody = document.getElementsByTagName('body').item(0);

		eltNotify = document.createElement('div');
		eltNotify.setAttribute('id', strMssgBoxId);
		eltNotify.style.display = 'none';

		eltNotify.innerHTML = 'Copied';

		eltBody.appendChild(eltNotify);
	}
	elt.onblur =
		function(e){
			Element.hide(eltNotify);
			return true;
		}

	var z = Position.cumulativeOffset(elt);
	var x = z[0];
	var y = z[1];

	Element.show(eltNotify);

	if(navigator.appName == 'Microsoft Internet Explorer'){
		if(x < 100){
			eltNotify.style.left = (x + (elt.offsetWidth - 23)) + 'px';
		}
		else{
			eltNotify.style.left = (x - (eltNotify.offsetWidth + 2)) + 'px';
		}
	}
	else{
		if(x < 100){
			eltNotify.style.left = (x + (elt.offsetWidth + 3)) + 'px';
		}
		else{
			eltNotify.style.left = (x - (eltNotify.offsetWidth + 2)) + 'px';
		}
	}

	eltNotify.style.top = y + 'px';

	var xEffect = Effect.Fade(eltNotify, { fps: 75, from: 1.9, to: 0.0, duration: 1.0, queue: 'front' } );
	window.status = 'Copied text to clipboard';

	// Copy the text inside the text box to the user's clipboard
	var flashcopier = 'flashcopier';
	if(!$(flashcopier)){
		var divholder = document.createElement('div');
		divholder.id = flashcopier;
		document.body.appendChild(divholder);
	}

	$(flashcopier).innerHTML = '';
	var divinfo = '<embed src="' + urlSwf + '" FlashVars="clipboard='+escape(elt.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
	$(flashcopier).innerHTML = divinfo;

	elt.select();

	return true;
}

// fireMouseEvent synthesises a mouse event on an element
// usage: fireMouseEvent($('someid'), 'click');

function fireMouseEvent(elt, strEvent)
{
	// Note: strEvent = Event name w/o "on" prefix (Ex: "click")
	if(typeof(elt) != "undefined" && elt && typeof(strEvent) == "string" && strEvent.length > 0){
		var objEvnt; // Synthetic Event Obj
		// Sythesize Click event
		if(document.createEvent){	// W3C
			objEvnt = document.createEvent('MouseEvents');
			objEvnt.initEvent(strEvent, false, true);
			elt.dispatchEvent(objEvnt);
		}
		else if(document.createEventObject){ // MSIE
			objEvnt = document.createEventObject();	// copy the original event to the new event object
			elt.fireEvent('on' + strEvent, objEvnt);
		}
	}
}

function magickAdRender(divName, aambTag) {
    var eltAdTarget;
    var invObj = 'INV' + divName;

    if((eltAdTarget = document.getElementById(divName)) != null){
        try{
            var code = aambTag;
        }
        catch(aamErr){
        }

        if(typeof(code) != 'undefined'){
            var msieIdx = navigator.userAgent.indexOf('MSIE');
            if(msieIdx > -1){
                var ifrString = '<iframe name="' + invObj + '" width="0" height="0" frameborder="0" AAM_EVENT="javascript:try { document.getElementById(\'' + divName + '\').insertAdjacentElement(\'beforeEnd\', window.frames[\'' + invObj + '\'].document.getElementById(\'adDiv\')) } catch(aamErr) { }"></iframe>';
                eltAdTarget.innerHTML += '<div id="TMP' + divName + '" style="display:none">' + escape('<body><div id="adDiv">' + code + '</div>') + '</div>' + ifrString.replace(/AAM_EVENT/, 'onload');
                window.frames[invObj].document.location = 'javascript:unescape(parent.document.getElementById(\'TMP' + divName + '\').innerHTML)';
            }
            else{
                document.writeln('<div id="' + invObj + '" style="display:none">' + code + '<script type="text/javascript" defer="true">document.getElementById(\'' + divName + '\').innerHTML = document.getElementById(\'' + invObj + '\').innerHTML;document.getElementById(\'' + invObj + '\').innerHTML = \'\';</scr' + 'ipt></div>');
            }
        }
    }
}
