/*
    Scripts that the site requires to function at its best
*/
var pageTracker = null;

$(document).ready(function(){
if ($(".itemVideo")){
    $(".itemVideo").click(function(e){  
		var currentVideo = $(this);
		e.preventDefault();
		$.nyroModalManual({        
			bgColor: '#000', 
			url: currentVideo.attr("href"),
			minHeight: 320,
			minWidth: 400,
			closeButton:'', 
			titleFromIframe: false, 
			autoSizeable: false        
		});        
		$("#nyroModalWrapper").append('<div style="width: 100%; background-color: #fff; float: left;padding-bottom: 5px;"><img src="/images/slimbox/sb_closelabel.gif" alt="Close" title="Close" onclick="closeModal();" style="float: right; cursor: pointer; padding-right: 10px;" /></div>');
    
		return false;
   });
   }
	setYellowGoogleTracking();
});


function setYellowGoogleTracking() {
if ($('.poweredBy')) {
	$('.poweredBy').click(function() {
		pageTracker._trackEvent('Yellow', 'Logo_Clicked', '[logo click]');
	});
	}
}
var closeModal = function()
{
    $.nyroModalRemove();
}

var logAnalyticsPageView = function(pageName)
{
    if(pageTracker && pageTracker != null)
    {
        pageTracker._trackPageview(pageName);
    }
}

function setupEmailSeller() {
	if ( !( jq.browser.msie && jq.browser.version == '6.0' ) && isEmail )
	{
		jq(".removable").attr("class", "collapsed");
		jq(".extendable").attr("class", "expanded");
		jq("a.send").click(setupModal);
	}
	else
	{
	    jq("a.send").click(function(){
	        if(!validateEmailText("#EmailForm input:first", "Please enter a valid email"))
	        {
	            logAnalyticsPageView('/Exclude/Used/EnquiryForm/ValidationError');
	        }
	        else
	        {
	            logAnalyticsPageView('/Exclude/Used/EnquiryForm/Success');
	            __doPostBack("ctl00$MasterHolder$itemdet$emailControl$Send", "");
	            //WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MasterHolder$itemdet$emailControl$Send", "", true, "EmailSeller", "", false, true));
	        }
	        
	        return false;
	    });
	}
};

var setupModal = function() {
	logAnalyticsPageView('/Used/EnquiryPopupForm');
	
	var modalIntro = "<p>Thank you for expressing interest in this " + singularName + ". Before sending your message we need to get your reply email address.</p>";
	var modalHeader = "<h3>Email Seller</h3>";
	var modalEmail = '<label for="">Your Email</label><input type="text" id="SenderEmail" value="' + jq("input.collapsed").val() + '" />';
	var modalMessage = "";
	var message = jq("#EmailForm textarea").val();
	if ( message && message != "" )
	{
		if ( message.length > 100 )
		{
			message = message.substr(0, 100) + "...";
		}
		modalMessage = '<label>Your Message</label><p class="message">' + message + '</p>';
	} 
	var modalFieldset = '<fieldset><a href="#" class="cancel" title="Cancel">Cancel</a><a href="#" class="send" title="Send Question">Send Question</a></fieldset>';
	var modalContent = modalHeader + modalIntro + modalEmail + modalMessage + modalFieldset;
	jq('<div class="modalContainer">').insertAfter("#emailSeller").fadeTo(500,0.85);
	jq('<div class="modalFrame modalMedium emailSellerModal">' + modalContent + '</div>').insertAfter("#emailSeller").css({display: "none"}).fadeIn(500);
	jq('.emailSellerModal a.send').click(sendEmail);
	jq('.emailSellerModal a.cancel').click(cancelSendEmail);
	return false;
}

var sendEmail = function() {
	var email = jq("#SenderEmail").val();
	if ( validateEmailText('#SenderEmail', 'You must enter a valid email address.') )
	{
	    logAnalyticsPageView('/Exclude/Used/EnquiryPopupForm/Success');
		jq("input.collapsed").val(email);
		__doPostBack("ctl00$MasterHolder$itemdet$emailControl$Send","");
		//WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MasterHolder$itemdet$emailControl$Send", "", true, "EmailSeller", "", false, true));
	}
	else
	{
	    logAnalyticsPageView('/Exclude/Used/EnquiryPopupForm/ValidationError');
	}
	return false;
}

var validateEmailText = function(emailInputElementSelector, messageForInvalidEmail)
{
    var emailInputElement = jq(emailInputElementSelector);
    if(emailInputElement == null) return false;
    
    var email = emailInputElement.val();
    var valid = (email && email != "" && email.match( /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/));
    
    if(!valid)
    {
        var validateMessage = jq("#validateSenderEmail");
		if ( validateMessage.length == 0 )
		{
			jq('<p id="validateSenderEmail" style="color: red;">' + messageForInvalidEmail + '</p>').insertAfter(emailInputElementSelector);
		}
        return false;
    }
    
    return true;
}

var cancelSendEmail =  function() {
    logAnalyticsPageView('/Exclude/Used/EnquiryPopupForm/Cancel');
	var cont = jq('.modalContainer').fadeOut(500, remove);
	var frame = jq('.modalFrame').fadeOut(500, remove);
	return false;
}

var remove = function() {
	jq(this).remove();
}

function ToggleSearch()
{
    var searchBar = m$("searchExtend");
    if (searchBar.style.display == "block") searchBar.style.display = "none";
    else searchBar.style.display = "block";
}

function EmailAFriend(control) {
    newWindow = window.open(control.href,'EmailAFriend','toolbar=0,top=20, location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=520,height=420');
    if (newWindow) newWindow.focus();
    return false;
}

function ShowDiv(sender, index)
{
    // Get all the divs
    var divs = sender.parentNode.parentNode.parentNode.getElementsByTagName("div");
    
    for(i = 0; i < divs.length; i++)
    {
        if(i == index)
            divs[i].style.display="block";
        else
            divs[i].style.display="none";
    }
    
    var lis = sender.parentNode.parentNode.getElementsByTagName("li");
        
    for(j = 0; j < lis.length; j++)
    {
        lis[j].className = "";
    }
    
    sender.parentNode.className = "selected";
}

function catchSearchSubmit(e)
{
    var key = e.keyCode ? e.keyCode : e.which;
    if (key == 13)
    {
	    e.cancelBubble = true;
	    e.returnValue = false;
	    //click button - MSN header hack, dont remove
	    setTimeout("__doPostBack('ctl00$searchBar$SearchButton','')", 1);
    }
}

function disableAllInputs()
{
    disableElementsInList(document.getElementsByTagName('input'));
    disableElementsInList(document.getElementsByTagName('select'));
    disableElementsInList(document.getElementsByTagName('textarea'));
}

function disableElementsInList(list)
{
    for (i=0; i < list.length; i++)
        disableElement(list[i]);
}

function disableElement(element)
{
    element.disabled = "disabled";
}
function setClassName(elId, cName)
{
    var el = document.getElementById(elId);
    
    if (el) 
    {
      el.className = cName;
      // change msn banner order
      var separators = getElementsByClassName("msnBanner", "div");
      if (separators) 
      {
        var separatorNode = separators[0];
        var parentNode = separatorNode.parentNode;
        var nodes = parentNode.childNodes;
        var index = 0;
        
        if (cName == 'resultsGallery') {
          index = 3;          
        }
        if (cName == 'resultsList') {
          index = 2;
        }
        // count the valid nodes and update index
        var found = false;
        var count = 0;
        var countDivs = 0;
        
        var thirdElement
        var fourthElement
        
        while(!found && count < nodes.length)
        { 
          if(nodes[count].nodeType == 1)
          {
            countDivs++; // count valid nodes (divs)
          }
          if(countDivs == 3){ thirdElement = nodes[count];}
          if(countDivs == 4)
          { 
            fourthElement = nodes[count];
            found = true;
          }
          count++;                    
        }
        
        if (index == 2 || index == 3)
        {  
            var destinationNode 
            if (index == 2)
              destinationNode = thirdElement;
            if (index == 3)
              destinationNode = fourthElement;
              
            if(destinationNode != separatorNode)
            {
              var newSeparatorNode = separatorNode.cloneNode(true);
              var newDestinationNode = destinationNode.cloneNode(true);
              parentNode.replaceChild(newDestinationNode, separatorNode);
              parentNode.replaceChild(newSeparatorNode, destinationNode);
            }          
        }
      }
    }
    else return;
    //random var to force IE to not use cache
    var rand = new Number(Math.round(Math.random() * Math.pow(2,24)));
    //set session for view
    //new Ajax("/SetResultsView.aspx?view=" + cName + "&rand=" + rand, {method:'get', onFailure: handleAjaxError, onComplete: handleSetViewSuccess}).request();
    $.ajax({
            type: 'GET',
            url: "/SetResultsView.aspx?view=" + cName + "&rand=" + rand,
            dataType: 'json'
        });
}
//function handleSetViewSuccess(jsonResponse) 
//{
//    alert(jsonResponse);
//}

/* PREVIEW AS YOU TYPE */
function popText(tb, id) { m$(id).innerHTML = escapeHTML(tb.value); }
/* PREVIEW AS YOU TYPE */
function popTextPrefix(tb, prefix, id) { 
text = escapeHTML(tb.value);
prefixControl = m$(prefix);
if ( prefixControl != null )
{
    text = prefixControl.value + text;
}
m$(id).innerHTML = text; }
/* CASCADING DROPDOWNS */
var dependant;
function handleCascadeSuccess(jsonResponse) 
{
    var response = jsonResponse; //Json.evaluate(jsonResponse);
    dependant.options.length = 0;
    //$A(response).each(function(data) { dependant.options[dependant.options.length] = new Option(data.name , data.value);});
    $.each(response, function(n, data) { dependant.options[dependant.options.length] = new Option(data.name , data.value); });
    dependant.disabled = "";
}
function handleAjaxError(e) { 
  // window.location.href = "/500.aspx"; 
}
function cascadeSelect(select, id, href, table, itemtype, enexid, defVal, advertiserReference)
{
    dependant = m$(id);
    dependant.disabled = "disabled";
    var advRef = ""
    if (advertiserReference && advertiserReference != "")
      advRef = "&advertiserreference=" + advertiserReference; 
    
    //new Ajax("/" + href + "?itemtype=" + itemtype + "&tablename=" + table + "&parentvalue=" + select.value + "&enexid=" + enexid + "&defval=" + defVal, {method: 'post', onComplete: handleCascadeSuccess, onFailure: handleAjaxError, postBody:'&_='}).request();
    $.ajax({
            type: 'POST',
            url: '/' + href + "?itemtype=" + itemtype + "&tablename=" + table + "&parentvalue=" + select.value + "&enexid=" + enexid + "&defval=" + defVal + advRef,
            data: '&_=',
            dataType: 'json',
            success: function(data){ handleCascadeSuccess(data); },
            error: handleAjaxError            
        });
}

/// Syntatic sugar
function m$(id) { return document.getElementById(id); }
function m$$(name) { return document.getElementsByName(name); }
function escapeHTML(str) { return document.createTextNode(str).nodeValue; }

function getElementsByClassName(clsName,tag)
{
    if(!tag) tag="*";
    var retVal = new Array();
    var elements = document.getElementsByTagName(tag);
    for(var i = 0;i < elements.length;i++){
        if(elements[i].className.indexOf(" ") >= 0){
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++){
                if(classes[j] == clsName)
                    retVal.push(elements[i]);
            }
        }
        else if(elements[i].className == clsName)
            retVal.push(elements[i]);
    }
    return retVal;
}
