
 function getRequest(){
    var request = false;
    if (window.XMLHttpRequest) // if Mozilla, Safari etc
        request = new XMLHttpRequest();
    else if (window.ActiveXObject){ // if IE
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e){
            try{
                request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e){}
        }
    }
    else
        return false;

    return request;
}

function expandAttributes(uuid){
    var page_request = getRequest();
    page_request.onreadystatechange=function(){
      loadJSON(page_request);
    }
    page_request.open('POST', '/expandDeviceAttributeChildren.do', true);
    page_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    var params = "uuid="+uuid;
    page_request.send(params);
}
function loadJSON(request){
    if (request.readyState == 4 && (request.status==200 || window.location.href.indexOf("html")==-1)){
        var messages = [];
        try {
            messages = YAHOO.lang.JSON.parse(request.responseText);
        }
        catch (x) {
            alert("JSON Parse failed!");
            return;
        }
         attributes = new YAHOO.widget.TreeView("attributes_tree");
        var root = attributes.getRoot();
        var innerAttributes = messages;
        for (var i=0; i < innerAttributes.length; i++) {
            YAHOO.sedw.createTreeNode(innerAttributes[i], root);
        };
        attributes.draw();

    }
}

 function updateCriteria(){
     var page_request = getRequest();
     page_request.onreadystatechange=function(){
       loadCriteriaJSON(page_request);
     }
     page_request.open('POST', '/device/getCriteriaJSON.do', true);
     page_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     page_request.send();
 }
 function loadCriteriaJSON(request){
     if (request.readyState == 4 && (request.status==200 || window.location.href.indexOf("html")==-1)){
         var messages = [];
        try {
            messages = YAHOO.lang.JSON.parse(request.responseText);
        }
        catch (x) {
            alert("JSON Parse failed!");
            return;
        }
         criteria = new YAHOO.widget.TreeView("criteria_tree");
        var root = criteria.getRoot();
        var attributes = messages;
        for (var i=0; i < attributes.length; i++) {
            YAHOO.sedw.createTreeNode(attributes[i], root);
        };
        criteria.draw();
     }
 }

function search(searchPopup){
    var attributeParams = "";
    var uuidParams = "";
    var firstAttributeFound = false;
    for (var i = 0; i < searchPopup.form.elements.length; i++) {
     if (searchPopup.form.elements[i].type == 'checkbox' && searchPopup.form.elements[i].checked){
         if (firstAttributeFound){
             attributeParams = attributeParams + "&";
         }
         firstAttributeFound = true;
         attributeParams = attributeParams +  "attributes=" + searchPopup.form.elements[i].value;
     }
     if (i != 0){
         uuidParams = uuidParams + "&";
     }
     uuidParams = uuidParams + "uuids=" + searchPopup.form.elements[i].value;
    }
    var params = attributeParams;
    if (params != ""){
        params = params + "&";
    }
    params = params + uuidParams;
    var page_request = getRequest();
    page_request.onreadystatechange=function(){
      updateSearchResults(page_request);
    }
    page_request.open('POST', '/device/attributeSubmit.do', true);
    page_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    page_request.send(params);

 }
 function updateSearchResults(request){
    if (request.readyState == 4 && (request.status==200 || window.location.href.indexOf("html")==-1)){
        document.getElementById("results").innerHTML = request.responseText
        YAHOO.util.Event.onAvailable("criteria_popup", YAHOO.sedw.init_criteria_popup);
    } else {
        document.getElementById("results").innerHTML = '<html><body>searching...</body></html>';
    }
 }


// taken from KPI example
function submitRating(contentId, path, rating) {
    //submit via xmlhttprequest so we dont hold things up
    var page_request = getRequest();
     page_request.onreadystatechange=function(){
      updatePageForRatings(page_request, path, contentId, rating);
    }
    var url = "/rateContent.do?contentId="+contentId+"&path="+path+"&rating="+ rating;
    page_request.open("POST",url,true);
    page_request.send(null);
}

function updatePageForRatings(request, path, contentId, rating) {
   if (request.readyState == 4 && (request.status==200 || window.location.href.indexOf("http")==-1) ){
        var ratingInfo = eval('(' + request.responseText + ')');

        var userRating;
        if (path != ''){
            userRating =  document.getElementsByName("rating" + path);
        } else {
            userRating =  document.getElementsByName("rating" + contentId);
        }
        for (var j = 0; j < userRating.length; j++){
          userRating [j].className="force-" + rating + "-star";
        }
        var aveRatings = document.getElementsByName("aveRating");
        for (var i = 0; i < aveRatings.length; i++){
          var aveRating = (ratingInfo.aveRating/ 5) * 100;
          aveRatings[i].style.width= aveRating + '%';
        }
       var numRatings = document.getElementsByName("numRating");
       for (var k = 0; k < numRatings.length; k++){
          numRatings[k].innerHTML=ratingInfo.numberOfRatings;
       }
    }
}

/* taken from registration form on current SEDW */
function submitForm() {
    //ERASER TC text as we dont really need it posted back, can cause problems with request objects
    if (testIsValidObject(document.forms.userRegistrationForm.terms)) {
        document.forms.userRegistrationForm.terms.value = '';
    }
    document.forms.userRegistrationForm.submit();
    return false;

}
    
/* taken from registration form on current SEDW */
function testIsValidObject(objToTest) {
    if (null == objToTest) {return false;}
    return "undefined" != typeof(objToTest);
}

/* New javascript starts below */

YAHOO.namespace("sedw");  // namespace for new js added

YAHOO.sedw.prev_doc = function(e, manager) {
    var active_doc = manager.getActive();
    if (e) {YAHOO.util.Event.preventDefault(e);}
    if (active_doc) {
        var prev_doc;
        for (var i=0; i < docs_modules.length; i++) {
            if(docs_modules[i].id == active_doc.id) {
                if (i == 0) {
                    prev_doc = docs_modules[manager.overlays.length - 1];
                } else {
                    prev_doc = docs_modules[i - 1];
                }
                // hide old doc and setup the previous one
                active_doc.hide();
                prev_doc.show();
                prev_doc.focus();
                break;
            }
        };
    }
}

YAHOO.sedw.next_doc = function(e, manager) {
    var active_doc = manager.getActive();
    if (e) {YAHOO.util.Event.preventDefault(e);}
    if (active_doc) {
        var next_doc;
        for (var i=0; i < docs_modules.length; i++) {
            if(docs_modules[i] == active_doc) {
                if (i == docs_modules.length - 1) {
                    next_doc = docs_modules[0];
                } else {
                    next_doc = docs_modules[i + 1];
                }
                // hide old doc and setup the next one
                active_doc.hide();
                next_doc.show();
                next_doc.focus();
                break;
            }
        };
    }
}

YAHOO.sedw.init_docs_rotate = function() {
    docs_manager = new YAHOO.widget.OverlayManager();
    docs_modules = [];
    var docs = YAHOO.util.Dom.getElementsByClassName("doc-item", "div", "doc-rotate");

    // for each group of doc-items found make it a Panel and add to Overlay Manager
    for (var i=0; i < docs.length; i++) {
      var cfg = {width: "675px", visible: false	};
      var panel = new YAHOO.widget.Panel(docs[i], cfg);
      docs_manager.register(panel);
      docs_modules[docs_modules.length] = panel;
    };

    // Fire up the first panel
    if (docs_manager.overlays.length > 0) {
      docs_manager.overlays[0].show();
      docs_manager.overlays[0].focus();
    }

    // Add onclick events for button controls and a rotater timer
    YAHOO.util.Event.on("doc_prev", "click", YAHOO.sedw.prev_doc, docs_manager, true);
    YAHOO.util.Event.on("doc_next", "click", YAHOO.sedw.next_doc, docs_manager, true);
    YAHOO.lang.later(12000, "doc-rotate", function() {YAHOO.sedw.next_doc(null, docs_manager);}, null, true);
}

YAHOO.sedw.button_tab_shadows = function(tabview) {
    var el = this.get('element');
    var content = YAHOO.util.Dom.getElementsByClassName('closed', 'div', el);
    if (content) {
        // remove closed class to add borders back to content box
        YAHOO.util.Dom.removeClass(content[0], 'closed');
    }
    // add shadow-box class for shadows
    YAHOO.util.Dom.addClass(el, 'shadow-box');
}

/*
    init_button_tabs
    Adds a TabView and a subscribed event to add/manipulate drop shadows.
    Just give it the id of the div element containing the TabView
    Example:
    
        YAHOO.sedw.init_button_tabs("rssmarks");

*/

YAHOO.sedw.init_button_tabs = function(el) {
    var tabview = new YAHOO.widget.TabView(el);
    tabview.addListener('beforeActiveTabChange', YAHOO.sedw.button_tab_shadows, tabview, true);
}

/*    Rotator for Hero Tabs on Homepage */
YAHOO.sedw.next_tab = function(tabview) {
    var tab_length = tabview.get('tabs').length;
    var tab_index = tabview.get('activeIndex');

    if (tab_index == tab_length - 1) {tab_index = 0;}
    else {tab_index++;}

    tabview.set('activeIndex', tab_index);
}

/* Quick setup for TreeView in RSS Button Tab */
YAHOO.sedw.init_feed_buttons = function() {
    rss_tree = new YAHOO.widget.TreeView("rss_tree");
    var root = rss_tree.getRoot();

    var html = '<div><a href="http://developer.sonyericsson.com/trackExternalLink.do?section=RSSADDON&uri=http://us.rd.yahoo.com/my/atm/Sony%20Ericsson%20Developer%20World/News/*http://add.my.yahoo.com/rss?url=http://developer.sonyericsson.com/site/rss/p_rss.xml"><img src="/images/content/my_yahoo.gif" alt=" My Yahoo"></a><br><a href="http://developer.sonyericsson.com/trackExternalLink.do?section=RSSADDON&uri=http://www.newsgator.co.uk/ngs/subscriber/subext.aspx?url=http://developer.sonyericsson.com/site/rss/p_rss.xml"><img src="/images/content/newsgator.gif" alt="NewsGator"></a><br><a href="http://developer.sonyericsson.com/trackExternalLink.do?section=RSSADDON&uri=http://fusion.google.com/add?feedurl=http://developer.sonyericsson.com/site/rss/p_rss.xml"><img src="/images/content/google.gif" alt="Google"></a>';

    var rss_news = new YAHOO.widget.TextNode("<a href='/site/rss/p_rss.xml'>新闻及文档</a>", root, true);
    var rss_news_content = new YAHOO.widget.HTMLNode(html, rss_news, false);
    
    
    rss_tree.draw();
}

/*
 * This is a new method to create a tree node for any tree, along with the node's
 * children by means of recursion. It works with the enhanced JSON tree structure
 * that is demonstrated in the body of the phone_gallery.html page.
 */
YAHOO.sedw.createTreeNode = function(nodeData, parent) {
	var tmp_node = null;
	var label = (YAHOO.lang.isObject(nodeData))?nodeData.label:nodeData;
	var expanded = (YAHOO.lang.hasOwnProperty(nodeData, "expanded"))?nodeData.expanded:false;
	var type = (YAHOO.lang.hasOwnProperty(nodeData, "type"))?nodeData.type:"text";
    var uuid = (YAHOO.lang.hasOwnProperty(nodeData, "uuid"))?nodeData.uuid:null;
    if (type == "task") {
		var checked = (YAHOO.lang.hasOwnProperty(nodeData, "checked"))?nodeData.checked:false;
		tmp_node = new YAHOO.widget.TaskNode(label, parent, expanded, uuid, "attributes", checked);
	}
	else {
		tmp_node = new YAHOO.widget.NavNode(label, parent, expanded, uuid);
	}
	if (YAHOO.lang.isArray(nodeData.children)) {
		for (var i = 0;i < nodeData.children.length; i ++) {
			YAHOO.sedw.createTreeNode(nodeData.children[i], tmp_node);
		}
	}
}

/*
 * Initializes the main tree for the gallery, to be placed on the left-hand side
 * of the document body. Note the much simplified code relative to earlier deliveries
 * which is made possible by the use of the recursive 'createTreeNode' method.
 * 
 * The data (YAHOO.sedw.attributes) is declared in-line in the phone_gallery.html
 * page.
 */
YAHOO.sedw.init_gallery = function () {
    tree = new YAHOO.widget.TreeView("gallery_attributes");
    var root = tree.getRoot();
    var attributes = YAHOO.sedw.attributes;
    for (var i=0; i < attributes.length; i++) {
		YAHOO.sedw.createTreeNode(attributes[i], root);
    };
    tree.draw();

    // Subscribe to the event labelClick (when a node is clicked)
    //     if it's a leaf of our phone gallery tree
    //     move the dialog box alongside it

    tree.subscribe("labelClick", function(node){
       	if (!node.hasChildren()) {
           	var x = YAHOO.util.Dom.getX(node.getEl());
           	var y = YAHOO.util.Dom.getY(node.getEl());
           	attr_popup.moveTo(x + 160, y-8);
		/*
		 * Do async request here to load attribute data.
		 * For demo purposes we just use our get method on our static, client-side data.
		 * The method call, along with the call to the popup.show method would also be 
		 * moved to the 'success' handler of the async call, assuming your AJAX 
		 * framework uses callbacks instead of pausing execution until the call returns.
		 */
			YAHOO.sedw.get_attributes(node.uuid);
            attr_popup.show();
       } 
    });
    // add events for our control links Expand/Collapse All
    YAHOO.util.Event.on("expand_tree", "click", 
		function(e){
			YAHOO.sedw.popup_manager.hideAll();
			tree.expandAll();
		}, tree, true);
    YAHOO.util.Event.on("collapse_tree", "click", 
		function(e){
			YAHOO.sedw.popup_manager.hideAll();
			tree.collapseAll();
		}, tree, true);
}

/*
 * Initializes the tree for the attributes popup. 
 * 
 * The data (YAHOO.sedw.level2Attributes) is declared in-line in the phone_gallery.html
 * page.
 * 
 * In production this client-side declaration should be replaced with an asynchronous 
 * call to the server (which will return the JSON data in string format and parsed via
 * the YUI JSON utility: http://developer.yahoo.com/yui/examples/json/json_connect.html
 */
YAHOO.sedw.get_attributes = function(uuid) {
   expandAttributes(uuid);
}

/*
 * Initializes the tree for the criteria popup. 
 * 
 * The data (YAHOO.sedw.criteriaAttributes) is declared in-line in the phone_gallery.html
 * page.
 * 
 * In production this client-side declaration should be replaced with an asynchronous 
 * call to the server (which will return the JSON data in string format and parsed via
 * the YUI JSON utility: http://developer.yahoo.com/yui/examples/json/json_connect.html
 */
YAHOO.sedw.get_criteria = function() {
    updateCriteria();
}

/* This method initializes the attributes popup, itself. But not the data. That
 * will be loaded via asynchronous call at every click of a leaf node in the tree
 * contained in the left-hand side of the document body.
 * 
 * This method is called when the 'onAvailable' event fires for the HTML elements
 * relevant to it. You can find the handler for this event set in phone_gallery.html.
 */
YAHOO.sedw.init_attributes_popup = function() {
    var handleCancel = function(e) {
        YAHOO.util.Event.preventDefault(e);
        this.cancel();
    }
    var handleUpdate = function() {
        search(this);
        this.cancel();
    }
	var buttons = [{text: "Update", handler:handleUpdate, isDefault: true},];
    attr_popup = new YAHOO.widget.Dialog("attributes_popup",
        {
            buttons: [
                {text: "Update", handler:handleUpdate, isDefault: true}
            ],
            context: ["gallery_attributes", "tl", "bl", "tr"],
            height: "293px",
            width: "273px",
            close: false,
            draggable: false,
            underlay: false,
            visible: false
        });
    attr_popup.render();
	
	// Hack to add the cancel link to the footer instead of the standard button
	attr_popup.footer.innerHTML = "<a href=\"#\" id=\"attr_popup_cancelLink\" class=\"link_highlight\">Cancel</a>&nbsp;" + attr_popup.footer.innerHTML;
	// Add an event handler to the cancel link's click event to close the dialog
	YAHOO.util.Event.addListener("attr_popup_cancelLink", "click", handleCancel, attr_popup, true);

    // add events for our control links Check/UnCheck All
    YAHOO.util.Event.on("attrib_check", "click", 
		function(e){
			attributes.expandAll();
			YAHOO.sedw.check_all(e, attr_popup.id);
		}
	);
    YAHOO.util.Event.on("attrib_uncheck", "click", 
		function(e){
			attributes.expandAll();
			YAHOO.sedw.uncheck_all(e, attr_popup.id);
		}
	);

    // Add to Overlay Manager
    if (YAHOO.sedw.popup_manager) {
        YAHOO.sedw.popup_manager.register(attr_popup);
    }
	
	/* Begin resize code */
	
    // Create Resize instance, binding it to the 'resizablepanel' DIV 
    var resize = new YAHOO.util.Resize('attributes_popup', {
        handles: ['br'],
        autoRatio: false,
        minWidth: 273,
        minHeight: 293,
		animate: false,
		status: false
    });

    // Setup resize handler to update the size of the Panel's body element
    // whenever the size of the 'resizablepanel' DIV changes
    resize.on('resize', function(args) {
		var bodyDiv = YAHOO.util.Dom.get("attributes_popup_bd");
        YAHOO.util.Dom.setStyle(bodyDiv, 'height', args.height-40 + 'px');
    }, attr_popup, true);
			
	// When hiding the popup reset the size to it's starting value.
	attr_popup.hideEvent.subscribe(function(){
		resize = resize.reset();
	}, this);
			
	/* End resize code */
}

/* This method initializes the criteria popup, itself. But not the data. That
 * will be loaded via asynchronous call at every click of the 'View Current Criteria'
 * link at the top of the document body.
 * 
 * This method is called when the 'onAvailable' event fires for the HTML elements
 * relevant to it. You can find the handler for this event set in phone_gallery.html.
 */
YAHOO.sedw.init_criteria_popup = function() {
	var showCritPopup = function(e) {
		YAHOO.util.Event.preventDefault(e);
		/*
		 * Do async request here to load criteria data.
		 * For demo purposes we just use our get method on our static, client-side data.
		 * The method call, along with the call to the popup.show method would also be
		 * moved to the 'success' handler of the async call, assuming your AJAX
		 * framework uses callbacks instead of pausing execution until the call returns.
		 */
		YAHOO.sedw.get_criteria();
	    this.show();
	}
    var handleCancel = function(e) {
        YAHOO.util.Event.preventDefault(e);
        this.cancel();
    }
    var handleUpdate = function() {
        search(this);
    }
    crit_popup = new YAHOO.widget.Dialog("criteria_popup",
        {
            buttons: [
                {text: "Update", handler:handleUpdate, isDefault: true}
            ],
            context: ["view_criteria", "tl", "bl"],
            height: "293px",
            width: "273px",
            close: false,
            draggable: false,
            underlay: false,
            visible: false
        });
    crit_popup.render();
	
	// Hack to add the cancel link to the footer instead of the standard button
	crit_popup.footer.innerHTML = "<a href=\"#\" id=\"crit_popup_cancelLink\" class=\"link_highlight\">Cancel</a>&nbsp;" + crit_popup.footer.innerHTML;
	// Add an event handler to the cancel link's click event to close the dialog
	YAHOO.util.Event.addListener("crit_popup_cancelLink", "click", handleCancel, crit_popup, true);

    // adjust popup to the left to align arrowed background better
    crit_popup.moveTo(crit_popup.cfg.config.x.value - 20, crit_popup.cfg.config.y.value);

    // Setup onclick event for current criteria popup
    YAHOO.util.Event.on("view_criteria", "click", showCritPopup, crit_popup, true);

    // add events for our control links Check/UnCheck All
    YAHOO.util.Event.on("crit_check", "click", 
		function(e){
			criteria.expandAll();
			YAHOO.sedw.check_all(e, crit_popup.id);
		}
	);
    YAHOO.util.Event.on("crit_uncheck", "click", 
		function(e){
			criteria.expandAll();
			YAHOO.sedw.uncheck_all(e, crit_popup.id);
		}
	);

    // Add to Overlay Manager
    if (YAHOO.sedw.popup_manager) {
        YAHOO.sedw.popup_manager.register(crit_popup);
    }
	
	/* Begin resize code */

    // Create Resize instance, binding it to the 'resizablepanel' DIV 
    var resize = new YAHOO.util.Resize('criteria_popup', {
        handles: ['br'],
        autoRatio: false,
		minWidth: 273,
        minHeight: 293,
		animate: false,
		status: false
    });

    // Setup resize handler to update the size of the Panel's body element
    // whenever the size of the 'resizablepanel' DIV changes
    resize.on('resize', function(args) {
		var bodyDiv = YAHOO.util.Dom.get("criteria_popup_bd");
        YAHOO.util.Dom.setStyle(bodyDiv, 'height', args.height-40 + 'px');
    }, crit_popup, true);
	
	// When hiding the popup reset the size to it's starting value.
	crit_popup.hideEvent.subscribe(function(){
		resize = resize.reset();
	}, this);
			
	/* End resize code */
}

/* Checks all checkboxes contained in element 'el' */
YAHOO.sedw.check_all = function(event, el) {
    var root = YAHOO.util.Dom.get(el);
    var inputs = root.getElementsByTagName("input");
    for (var i=0; i < inputs.length; i++) {
        if(inputs[i].getAttribute("type") == "checkbox") {
            inputs[i].checked = true;
        }
    };
    YAHOO.util.Event.preventDefault(event); 
}

/* Unchecks all checkboxes contained in element 'el' */
YAHOO.sedw.uncheck_all = function(event, el) {
    var root = YAHOO.util.Dom.get(el);
    var inputs = root.getElementsByTagName("input");
    for (var i=0; i < inputs.length; i++) {
        if(inputs[i].getAttribute("type") == "checkbox") {
            inputs[i].checked = false;
        }
    };
    YAHOO.util.Event.preventDefault(event);
}

/*
    Based on YUI grids columnfix
    written by Christian Heilmann (http://wait-till-i.com)

    Parameters:
        root - the container holding the columns
        class_name - a class name applied to the columns

    YAHOO.sedw.columnfix("two_column", "boxy");

*/

YAHOO.sedw.columnfix = function(root, class_name) {
    var set = YAHOO.util.Dom.get(root);
    var region = YAHOO.util.Dom.getRegion(set);
    var height = region.bottom - region.top;
    var columns = YAHOO.util.Dom.getElementsByClassName(class_name, 'div', set);
    for (var i=0; i < columns.length; i++) {
      YAHOO.util.Dom.setStyle(columns[i], 'height', height + 'px');
    };
} 
